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

发布于 2024-10-14 09:23:02 字数 260 浏览 3 评论 0原文

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

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

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

I have a database schema = which will be shown in a JCombobox as a JTable column to select a name. But I want the ID field to insert (as a foreign key) in another table.

Usually, selecting an Item in drop down, bring the selected item to the shown area of the combo box.

What I want to do is, when select any item (string) in the combo box its corresponding integer key (can be kept in a sorted map) should be shown in the combobox placeholder area, so that when take the value of the JTable.getValueAt(row, column), I get the integer key, not the string item value.
Please help me how can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

各自安好 2024-10-21 09:23:02

您应该在 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 );
     }

}

You should store an Object in the TableModel that contains both the string value to display and the Integer value for the key. Then you you access table.getValueAt(...) you have access to the object which contain both pieces of information.

Here is an example for a standalone combo box:

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

}
浊酒尽余欢 2024-10-21 09:23:02

我有一个很棒且聪明的解决方案:

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

我使用带有自定义对象的向量为 rolComboBox 设置模型,resultSet 对象包含数据库中的所有数据。
当我想从 comboBox 获取 id 时,使用方法 getSelectedItem 获取它。

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

I have a great and smart solution:

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

I set model for rolComboBox with a Vector with custom Object, the resultSet object contain all data from Data Base.
After when i want get the id from the comboBox get it with the method getSelectedItem.

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

因为没有自动的方法来做到这一点:(。
我正在使用地图来保存我的价值观和密钥。

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

Since there is no automatic way to do it :(.
I am using a Map to keep my values and key.

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

Get all the categories (key, value) and populate the map and combo

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

The fourth column of my JTable should be combobox,

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

When editing the value in the combobox, it show the text, but for updating the value in the database table I have to get the integer key.

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

For database update,

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

And here is the getKeyForValue,

private int getKeyForValue(String value) {
    for (Entry<Integer, String> entry : categoryMap.entrySet()) {
         if (entry.getValue().equals(value)) {
             return entry.getKey();
         }
     }
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文