Reputation: 1202
I am trying to display a selected item from a JComboBox (which I do get to display) but when I pass a ItemListener to see if it was deselected, the other label still shows up and it just overlaps the next label. Here is my code:
ItemListener itemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
int state = event.getStateChange();
JPanel select = new JPanel();
JLabel label = new JLabel("Department Selected: ");
JTextField selected = new JTextField(10);
switch (state) {
case ItemEvent.SELECTED:
String selection = (String) aDpts.getSelectedItem();
selected.setEditable(false);
selected.setText(selection);
select.add(label);
select.add(selected);
break;
case ItemEvent.DESELECTED:
label.removeAll();
selected.removeAll();
select.removeAll();
break;
}
add(select, BorderLayout.LINE_END);
}
Also, it won't show the label unless I resize the window..
Upvotes: 0
Views: 118
Reputation: 347184
You're creating a new instance of JLabel
EVERY time itemStateChanged
is changed, so you're attempting to remove a label from a container to which it was never added.
Instead, simply create a single JLabel
and update it's text
property
I'm scratching my head over why you would create a new instance of JLabel
, JPanel
and JTextField
when it seems like you are simply trying to update the previous states
Upvotes: 1