I made this code which should change the value in a JLabel after selecting an item from a combobox. When I run the application the appears in the JLabel but when I select other value in combobox, the value in JLabel isn't changing. Do anyone know where the problem is?
comboBox = new JComboBox<String>();
comboBox.setBounds(172, 50, 106, 22);
frmAccountPayable.getContentPane().add(comboBox);
comboBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
String expenseCode = item.toString();
try {
String sql2 = "SELECT `Account No`, `Expense Code` FROM `database`.`expense_code_master` " +
"WHERE `Expense Code` = '" + expenseCode + "'";
PreparedStatement pst2 = conn.prepareStatement(sql2);
ResultSet rs = pst2.executeQuery();
String accNo1 = null;
while (rs.next()){
accNo1 = rs.getString("Account No");
}
lblTesting = new JLabel(accNo1);
lblTesting.setBounds(496, 49, 106, 22);
frmAccountPayable.getContentPane().add(lblTesting);
}catch (Exception ex) {
System.out.println("Error: "+ex);
}
}
}
});
If you already have a JLabel
in your component, you don't need to recreate one for each state change.
Move that part to where you also add your comboBox
:
lblTesting = new JLabel(accNo1);
lblTesting.setBounds(496, 49, 106, 22);
frmAccountPayable.getContentPane().add(lblTesting);
But with the default constructor.
And instead of adding a new label each time, simply call:
lblTesting.setText(accNo1);
That being said, I guess that in your example you add new label, but only the first is displayed - depending on your layout.