How can I enable/disable my JTextField depending of the state of a JCheckBox?

Jeff picture Jeff · Aug 23, 2011 · Viewed 27.8k times · Source

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?

Answer

mre picture mre · Aug 23, 2011

Suggestion:

  1. Read the How to Use Check Boxes tutorial
  2. Register an ItemListener for the JCheckBox instance
  3. Compare state change (i.e. getStateChange()) 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();
        }
    }
}

enter image description here

enter image description here