java - 如何从组合框值传递到

标签 java swing combobox jcombobox

不知何故,我设法使该 id 不显示在组合框中,但是当我按下按钮时如何才能获得 id 值?按下按钮时使用 String from = (String) jComboBox1.getSelectedItem(); 不起作用。我得到了 String code = (String) item.getValue(); 我需要的 id,但是如何将它传递给下一个查询?

public void select() {

         try {
            String sql = "select * from category";
            pst = con.prepareStatement(sql);
            rs = pst.executeQuery();

            while (rs.next()) {

        jComboBox1.addItem(new Item<String>(rs.getString("mkid"), rs.getString("name")));

            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }

        jComboBox1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JComboBox jComboBox1 = (JComboBox) e.getSource();
                Item item = (Item) jComboBox1.getSelectedItem();
                String code = (String) item.getValue();
                System.out.println(code);
            }
        });


    }


    The item

     public class Item<V> implements Comparable<Item>
     {
    private V value;
    private String description;


    public Item(V value, String description)
    {
        this.value = value;
        this.description = description;
    }


    public V getValue()
    {
        return value;
    }

    public String getDescription()
    {
        return description;
    }

    public int compareTo(Item item)
    {
        return getDescription().compareTo(item.getDescription());
    }

    @Override
    public boolean equals(Object object)
    {
        Item item = (Item)object;
        return value.equals(item.getValue());
    }

    @Override
    public int hashCode()
    {
        return value.hashCode();
    }


    @Override
    public String toString()
    {
        return description;
    }

最佳答案

向按钮添加监听器,然后添加代码以将组合框值获取为字符串。

       JButton okButton = new JButton("OK");  
       okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            JComboBox jComboBox1 = (JComboBox) e.getSource();
            Item item = (Item) jComboBox1.getSelectedItem();
            String code = (String) item.getValue();
            System.out.println(code);
         }          
      });

关于java - 如何从组合框值传递到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067356/

相关文章:

java - 将 Json 字符串转换为 JSONArray

java - 使用涉及每个元素索引的计算在数组中赋值

java - 命令模式 - 返回一个值

javascript - 在触发器上单击 Extjs 3.4 重新加载 ComboBox 存储

java - 鼠标悬停 - 在屏幕上显示消息 Java 应用程序

java - 线条未出现在 JDesktopPane 上

java - 在 Linux 上使用 Swing «artifacts» 实现一个非常简单的 GUI 程序

java - 按下回车后的 JTextArea

java - 组合框中的项目

JavaFX : How to fill a ComboBox with changing values and refrech it