2015-06-19 116 views
1

我有一個JComboBox,我必須顯示產品的名稱,並且每個代碼都有一個代碼, 在我的數據庫中,我必須註冊產品代碼,但在Combo中我必須顯示指定,我該怎麼做才能在組合中顯示指定,但將其代碼保存在數據庫中?在JComboBox中顯示屬性並註冊另一個屬性

這是我返回代碼和名稱

public ResultSet GetDesignation(JComboBox des) 
{ 
ResultSet rs1 = null; 


try { 

conn=con.Connect(); 

stmt = conn.createStatement(); 
String rq1 = "SELECT designation, idproduit FROM produit"; 

rs1 = stmt.executeQuery(rq1); 
while (rs1.next()) { 
des.addItem(rs1.getString(1)); 

} 
stmt.close(); 

conn.close(); 

} catch (SQLException e) { 
e.printStackTrace(); 
} 
finally{ 


return rs1; 
} 
} 

代碼,這是我得到的idproduct(代碼)的代碼

m.GetDesignation(des); 
int designation=Integer.parseInt(des.getSelectedItem().toString()); 

回答

0

而不是JComboBox直接的人口,創造這樣一個產品類,並在您的while循環提取ID和產品名稱ResultSet的每次迭代中,並將其設置爲Product實例的屬性。添加該產品例如在一些收集像ArrayList,並用它來填充JComboBox

public class Product { 

    private int idProduct; 

    private String name; 


    public Product(int idProduct, String name) { 
     this.idProduct = idProduct; 
     this.name = name; 
    } 

    public int getIdProduct() { 
     return idProduct; 
    } 

    public void setIdProduct(int idProduct) { 
     this.idProduct = idProduct; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

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

設置DefaultComboBoxModelJComboBox和數據添加到模型:

import javax.swing.*; 
import java.awt.event.ItemEvent; 

public class ComboDemo { 
    public static void main(String[] args) { 
     JComboBox<Product> comboBox = new JComboBox<>(); 
     DefaultComboBoxModel<Product> defaultComboBoxModel = new DefaultComboBoxModel<>(); 
     comboBox.setModel(defaultComboBoxModel); 
     defaultComboBoxModel.addElement(new Product(1, "Apples")); 
     defaultComboBoxModel.addElement(new Product(2, "Oranges")); 

     comboBox.addItemListener(e -> { 
      if (e.getStateChange() == ItemEvent.SELECTED) { 
       Product product = (Product) comboBox.getSelectedItem(); 
       System.out.println(product.getName() + " ::: " + product.getIdProduct()); 
      } 
     }); 

     JOptionPane.showMessageDialog(null, comboBox); 
    } 
} 

JComboBox添加ItemListener和使用getSelectedItemJComboBox獲得Product。所以基本上,在這種情況下,您的JComboBox包含Product項目與他們的所有屬性,而不是String's在你的情況。

相關問題