I have a Java check box next to a text field.
When the check box gets selected, I want the text box to be enabled and when it isn't, I don't want it to be selected. I tried an if
statement with the isSelected()
method, but it didn't do anything.
How can I react to state changes of the JCheckBox?
Suggestion:
ItemListener
for the JCheckBox
instancegetStateChange()
) to either ItemEvent.SELECTED
, or ItemEvent.DESELECTED
, and then appropriately invoke foo.setEnabled
, where foo
is the JTextBox
instance.Here's an SSCCE:
public final class JCheckBoxDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("JCheckBox Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(JCheckAndTextPane.newInstance());
frame.setSize(new Dimension(250, 75)); // for demonstration purposes only
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JCheckAndTextPane extends JPanel{
private JCheckAndTextPane(){
super();
// Create components
final JTextField textField = new JTextField("Enabled");
final JCheckBox checkBox = new JCheckBox("Enable", true);
checkBox.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
textField.setEnabled(true);
textField.setText("Enabled");
}
else if(e.getStateChange() == ItemEvent.DESELECTED){
textField.setEnabled(false);
textField.setText("Disabled");
}
validate();
repaint();
}
});
add(checkBox);
add(textField);
}
public static final JCheckAndTextPane newInstance(){
return new JCheckAndTextPane();
}
}
}