Reputation: 3
The code I'm creating involves a JRadioButton and a JComboBox. I want the JComboBox to be enabled if the JRadioButton is selected and disabled if it's not selected or deselected. My problem is that the JComboBox won't be disabled if I deselect the JRadioButton. How can I do this? Here's my code
LouisClub=new JComboBox();
LouisClub.setEnabled(false);
LouisClub.addItem("Writer");
LouisClub.addItem("Photojournalist");
LouisClub.addItem("Cartoonist");
LouisClub.addItem("Layout Artist");
Louis=new JRadioButton("The Louisian");
Louis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LouisClub.setEnabled(true);
}
});
Upvotes: 0
Views: 934
Reputation: 1292
You should use an ItemListener instead of an ActionListener. Here is the code :
public class Toto extends JPanel {
private JComboBox LouisClub;
private JRadioButton Louis;
/**
* Create the panel.
*/
public Toto() {
LouisClub = new JComboBox();
LouisClub.setEnabled(false);
LouisClub.addItem("Writer");
LouisClub.addItem("Photojournalist");
LouisClub.addItem("Cartoonist");
LouisClub.addItem("Layout Artist");
Louis = new JRadioButton("The Louisian");
Louis.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean ok = e.getStateChange()==ItemEvent.SELECTED;
LouisClub.setEnabled(ok);
}
});
add(Louis);
add(LouisClub);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new Toto());
frame.pack();
frame.setVisible(true);
}
}
I have two more comments to make :
bye,
Jean-Marc
Upvotes: 1
Reputation: 59660
You should JCheckBox instead of JRadioButton for such things and then you need check for checkBox status in actionPerformed() method and based on that enable/disable comboBox. Something like
Louis=new JCheckBox();
Louis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LouisClub.setEnabled(((JCheckBox)e.getSource()).isSeleted());
}
}
Also it might be good (Not sure) to use ChangeListener instead of ActionListener.
Louis.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
LouisClub.setEnabled(((JCheckBox)ce.getSource()).isSeleted());
}
});
Upvotes: 1