如何从列表中隐藏jcombobox项目,但仍然使用它来从数据库表中获取数据

时间:2014-11-20 15:29:31

标签: java jquery database swing 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;
}

1 个答案:

答案 0 :(得分:1)

您需要创建一个自定义对象来包含您的数据,然后将自定义对象添加到模型中。然后,您需要使用自定义渲染器来显示此对象。

查看Combo Box With Custom Renderer以获取如何执行此操作的示例。