java - Display attribute in JComboBox and register another attribute -
i have jcombobox , must show designation of product, , each has code designation, in database have register product code in combo must show designation, how should display designation in combo save code in database?
this code return code , designation
public resultset getdesignation(jcombobox des) { resultset rs1 = null; try { conn=con.connect(); stmt = conn.createstatement(); string rq1 = "select designation, idproduit 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; } }
and code idproduct (code)
m.getdesignation(des); int designation=integer.parseint(des.getselecteditem().tostring());
instead of direct population of jcombobox
, create product class , in each iteration of while
loop extract id , product's name resultset
, set properties of product instance. add product instance in collection arraylist
, use populate 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; } }
set defaultcomboboxmodel
jcombobox
, add data model:
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); } }
add itemlistener
on jcombobox
, use getselecteditem
obtain product
jcombobox
. basically, in case, jcombobox
contains product
items properties instead of string's
in case.
Comments
Post a Comment