How can I enable/disable my JTextField depending of the state of a JCheckBox?
28,959
Solution 1
Suggestion:
- Read the How to Use Check Boxes tutorial
- Register an
ItemListener
for theJCheckBox
instance - Compare state change (i.e.
getStateChange()
) to eitherItemEvent.SELECTED
, orItemEvent.DESELECTED
, and then appropriately invokefoo.setEnabled
, wherefoo
is theJTextBox
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();
}
}
}
Solution 2
Use the isSelected
method.
You then use an ItemListener
so you'll be notified when it's checked or unchecked.
And depending on the state of the isSelected method, then you can enable or disable the JTextBox
.
Author by
Jeff
Updated on December 13, 2020Comments
-
Jeff over 3 years
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 theisSelected()
method, but it didn't do anything.How can I react to state changes of the JCheckBox?
-
Andrew Thompson almost 13 years2 notes. 1) An SSCCE should include the imports (not all of us run automagic IDEs that will figure them out!). 2) For tips on making great screen shots (especially getting rid of the 'stray pixels' in the rounded corners), see the How do I create screenshots? FAQ. Those 2 points aside, +1.