Please have a look at the following code
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ComboIssue extends JFrame
{
private JRadioButton rOne, rTwo;
private ButtonGroup group;
private JComboBox combo;
private JLabel label;
public ComboIssue()
{
rOne = new JRadioButton("One");
rOne.addActionListener(new ROneAction());
rTwo = new JRadioButton("Two");
rTwo.addActionListener(new RTwoAction());
group = new ButtonGroup();
group.add(rOne);
group.add(rTwo);
combo = new JComboBox();
combo.addItem("No Values");
combo.addItemListener(new ComboAction());
label = new JLabel("labellLabel");
this.setLayout(new FlowLayout());
this.add(rOne);
this.add(rTwo);
this.add(combo);
this.add(label);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ROneAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
combo.removeAllItems();
combo.addItem("One");
}
}
private class RTwoAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
combo.removeAllItems();
combo.addItem("Two");
}
}
private class ComboAction implements ItemListener
{
public void itemStateChanged(ItemEvent ie)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
label.setText("Selected");
}
}
}
public static void main(String[]args)
{
new ComboIssue();
}
}
Here what I am expecting is,
- Select one radio button. It will replace value in combo box.
- Select a value from the combo box. Now the JLabel text will be set to "Selected"
But, that is not what is happening. Instead, the JLabel text get changed as soon as you select a radio button!!! Why is this? Please help!