JCombobox字符串项(可见)和整数键(固有)

时间:2011-01-27 22:55:14

标签: java jtable jcombobox

我有一个数据库模式=它将作为JTable列显示在JCombobox中以选择名称。但我希望ID字段在另一个表中插入(作为外键)。

通常,在下拉列表中选择一个项目,将所选项目带到组合框的显示区域。

我想要做的是,当在组合框中选择任何项目(字符串)时,其对应的整数键(可以保存在有序映射中)应该显示在组合框占位符区域中,这样当取值时JTable.getValueAt(row,column),我得到整数键,而不是字符串项值。 请帮帮我怎么办?

3 个答案:

答案 0 :(得分:14)

您应该在TableModel中存储一个Object,其中包含要显示的字符串值和键的Integer值。然后你可以访问table.getValueAt(...),你可以访问包含两条信息的对象。

以下是独立组合框的示例:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxItem extends JFrame implements ActionListener
{
    public ComboBoxItem()
    {
        Vector model = new Vector();
        model.addElement( new Item(1, "car" ) );
        model.addElement( new Item(2, "plane" ) );
        model.addElement( new Item(3, "train" ) );
        model.addElement( new Item(4, "boat" ) );
        model.addElement( new Item(5, "boat aadf asfsdf a asd asd" ) );

        JComboBox comboBox;

        //  Easiest approach is to just override toString() method
        //  of the Item class

        comboBox = new JComboBox( model );
        comboBox.addActionListener( this );
        getContentPane().add(comboBox, BorderLayout.NORTH );

        //  Most flexible approach is to create a custom render
        //  to diplay the Item data

        comboBox = new JComboBox( model );
        comboBox.setRenderer( new ItemRenderer() );
        comboBox.addActionListener( this );
        getContentPane().add(comboBox, BorderLayout.SOUTH );
    }

    public void actionPerformed(ActionEvent e)
    {
        JComboBox comboBox = (JComboBox)e.getSource();
        Item item = (Item)comboBox.getSelectedItem();
        System.out.println( item.getId() + " : " + item.getDescription() );
    }

    class ItemRenderer extends BasicComboBoxRenderer
    {
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

            if (value != null)
            {
                Item item = (Item)value;
                setText( item.getDescription().toUpperCase() );
            }

            if (index == -1)
            {
                Item item = (Item)value;
                setText( "" + item.getId() );
            }


            return this;
        }
    }

    class Item
    {
        private int id;
        private String description;

        public Item(int id, String description)
        {
            this.id = id;
            this.description = description;
        }

        public int getId()
        {
            return id;
        }

        public String getDescription()
        {
            return description;
        }

        public String toString()
        {
            return description;
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxItem();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
     }

}

答案 1 :(得分:1)

我有一个很棒的智能解决方案:

ResultSet resultSet = userBL.loadRoles();
            try {
                Vector<Roles> vector = new Vector<>();
                while (resultSet.next()) {
                    vector.addElement(new Roles(resultSet.getInt(1), resultSet.getString(2)));                                                
                }
                rolComboBox.setModel(new DefaultComboBoxModel(vector));            
            } catch (SQLException e) {
                System.out.println("SQLException LoadRoles Combo:"+e);
            }

我使用带有自定义对象的Vector设置rolComboBox的模型,resultSet对象包含来自数据库的所有数据。 在我想要获取comboBox的ID后,请使用方法getSelectedItem

System.out.println("Rol Selected: "+ ((Roles)rolComboBox.getSelectedItem()).getId());

答案 2 :(得分:-2)

由于没有自动的方法:(。 我使用地图来保持我的价值观和关键。

private TreeMap <Integer, String> categoryMap = new TreeMap<Integer, String>();
private JComboBox comboCategory = new JComboBox();

获取所有类别(键,值)并填充地图和组合

private void addComboColumnData() {
        try {
            Class.forName("org.sqlite.JDBC");
            Connection conn = DriverManager.getConnection(conURL);
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery("SELECT id, name FROM categories");            
            comboCategory.removeAllItems();
            comboCategory.addItem(""); // blank value.
            categoryMap.clear();
            while(rs.next()){
                String name = rs.getString("name");
                comboCategory.addItem(name);
                categoryMap.put(rs.getInt("id"), name);
            }           
            rs.close();
            conn.close();
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, e.toString());
            e.printStackTrace();
        }
    }

我的JTable的第四列应该是组合框,

// set the fourth column as combo
            TableColumn categoryColumn = tableData.getColumnModel().getColumn(4);
            categoryColumn.setCellEditor(new DefaultCellEditor(comboCategory));

当编辑组合框中的值时,它会显示文本,但是为了更新数据库表中的值,我必须得到整数键。

// show Category name in text in the category field.
                    if(columnNames[i].equalsIgnoreCase("category")){
                        Object obj = rs.getObject(i+1);
                        if(obj != null && (obj instanceof Integer) )
                            row[i] = (String) categoryMap.get((Integer) obj);
                    }   

对于数据库更新,

Object value = tableData.getModel().getValueAt(rowIndex, 4);
        int categoryID = 0;

        if(value!= null){
            if (value instanceof String && !((String)value).isEmpty()) {
                categoryID = getKeyForValue((String)value);
            } else if(value instanceof Number) {
                categoryID = (Integer) value;
            }
        }

这是getKeyForValue,

private int getKeyForValue(String value) {
    for (Entry<Integer, String> entry : categoryMap.entrySet()) {
         if (entry.getValue().equals(value)) {
             return entry.getKey();
         }
     }
    return 0;
}