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

Java JCombobox字符串项(可见)和整数键(固有),java,jtable,jcombobox,Java,Jtable,Jcombobox,我有一个database schema=,它将作为JTable列显示在JCombobox中,用于选择名称。但是我希望ID字段(作为外键)插入到另一个表中 通常,在下拉列表中选择一个项目,将所选项目带到组合框的显示区域 我想做的是,当在组合框中选择任何项(字符串)时,其对应的整数键(可以保存在已排序的映射中)应该显示在组合框占位符区域中,以便在获取JTable.getValueAt(行、列)的值时,我得到的是整数键,而不是字符串项的值。 请帮助我如何执行此操作?您应该在TableModel中存储一

我有一个database schema=,它将作为JTable列显示在JCombobox中,用于选择名称。但是我希望ID字段(作为外键)插入到另一个表中

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

我想做的是,当在组合框中选择任何项(字符串)时,其对应的整数键(可以保存在已排序的映射中)应该显示在组合框占位符区域中,以便在获取JTable.getValueAt(行、列)的值时,我得到的是整数键,而不是字符串项的值。
请帮助我如何执行此操作?

您应该在TableModel中存储一个对象,该对象包含要显示的字符串值和键的整数值。然后访问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 );
     }

}

因为没有自动的方法来做这件事:(。 我使用地图来保存我的值和键

private TreeMap <Integer, String> categoryMap = new TreeMap<Integer, String>();
private JComboBox comboCategory = new JComboBox();
我的JTable的第四列应该是combobox

// 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;
}
private int getKeyForValue(字符串值){
for(条目:categoryMap.entrySet()){
if(entry.getValue().equals(value)){
return entry.getKey();
}
}
返回0;
}

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

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);
            }

有时候我讨厌java。对于一个简单的任务,有太多的代码
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);
            }
System.out.println("Rol Selected: "+ ((Roles)rolComboBox.getSelectedItem()).getId());