Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 809
Jeff Avatar asked Dec 04 '22 07:12

Jeff


1 Answers

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

like image 105
mre Avatar answered Dec 21 '22 10:12

mre