我想从我的数据库中获取包含2个字段的结果集。
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
然后我想在comboBox中显示名为“name_prov”的字段(作为项目)。但我也希望将我的“id_prov”作为ID(PRIMARY KEY)作为此项的值。这只是为了通过使用组合框将名称(在这种情况下是提供者)与其ID相关联。
这是我目前正在使用的JComboBox事件FocusGained的代码。
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
CBProvedores.addItem(rs.getString("name_prov"));
//Here should be the Value related to the item I am creating
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
无论如何我能做到这一点吗?
答案 0 :(得分:6)
首先创建一个POJO,它将包含您的name
和id
。
public class ComboItem {
private String id;
private String name;
public ComboItem(String id, String name) {
this.id = id;
this.name = name;
}
// Add the getter and setter as you want.
// This will be used internally by JComboBox as the label to be displayed.
@Override
public String toString() {
return name;
}
}
然后将此POJO对象放入JComboBox
。
try {
//CBProv is the Combobox
CBProv.removeAllItems();
rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");
while(rs.next())
{
String id = rs.getString("id_prov"); // Get the Id
String name = rs.getString("name_prov"); // Get the Name
ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
CBProv.addItem(comboItem); // Put it into the ComboBox
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error" + e );
}
然后最终获得选择的值,你可以这样做: -
CBProv.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
// comboItem.getId(), comboItem.getName() - Use as you wish.
}
});
答案 1 :(得分:0)
大家好,我还是java和javafx的新手。这就是我在javafx中所做的,它对我有用。希望你能在java中解决它。
private void fillProviders()
{
List<String> providerList = new ArrayList<String>();
try
{
String Sql = "select * from prov ";
pat= conn.prepareStatement(Sql);
rs=pat.executeQuery();
while (rs.next())
{
providerList.add(rs.getString("id_prov")+" "+ rs.getString("name_prov"));
}
ObservableList<String> provider = FXCollections.observableArrayList(providerList);
bankName.setItems(provider);
}
catch( Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
希望它适合你。请注意,我的组合框名称是bankName