i have this code and i want to get the selected item from jcombobox,but when i run my project it gives me duplication print of the value of the selected item and java.Lang.NullPointerException Here is the code :
private void jComboBox4ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
if (evt.getStateChange()==ItemEvent.SELECTED){
String a=String.valueOf(jComboBox4.getSelectedItem());
System.out.print(a);
try{
String del2="select distinct PTYPE from Projects inner join project on projects.PNUMBER=(select pro_id from project where pro_name='"+a+"')";
psst=con.prepareStatement(del2);
String td2;
DefaultComboBoxModel mode2 = new DefaultComboBoxModel();
ResultSet rss=psst.executeQuery();
while(rss.next()){
td2=rss.getString("PTYPE");
mode2.addElement(td2);
jComboBox7.setModel(mode2);
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex.toString());
}
}
You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.
Which event gets generated when you select an item from a JComboBox? Combo boxes also generate item events, which are fired when any of the items' selection state changes.
getItemCount() : returns the number of items in the list. getItemListeners(): returns an array of all the ItemListeners added to this JComboBox with addItemListener().
Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items.
I assume you have this code inside an itemStateChanged()
method. the reason you get it twice is that it happens for both selecting the new value and de-selecting the old value.
Your code should look something like:
myCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
String a=jcombobox.getselecteditem().toString();
System.out.print(a);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With