JPanel Action Listener

后端 未结 3 1684
不知归路
不知归路 2021-01-19 03:56

I have a JPanel with a bunch of different check boxes and text fields, I have a button that\'s disabled, and needs to be enabled when specific configurations are setup. What

3条回答
  •  佛祖请我去吃肉
    2021-01-19 04:30

    First off as @Sage mention in his comment a JPanel is rather a container than a component which do action. So you can't attach an ActionListener to a JPanel.

    I figure I can copy and paste my code a bunch of times into every listener in the panel, but that seems like bad coding practice to me.

    You're totally right about that, it's not a good practice at all (see DRY principle). Instead of that you can define just a single ActionListener and attach it to your JCheckBoxes like this:

    final JCheckBox check1 = new JCheckBox("Check1");
    final JCheckBox check2 = new JCheckBox("Check2");
    final JCheckBox check3 = new JCheckBox("Check3");
    
    final JButton buttonToBeEnabled = new JButton("Submit");
    buttonToBeEnabled.setEnabled(false);
    
    ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean enable = check1.isSelected() && check3.isSelected();
            buttonToBeEnabled.setEnabled(enable);
        }
    };
    
    check1.addActionListener(actionListener);
    check2.addActionListener(actionListener);
    check3.addActionListener(actionListener);
    

    This means: if check1 and check3 are both selected, then the button must be enabled, otherwise must be disabled. Of course only you know what combination of check boxes should be selected in order to set the button enabled.

    Take a look to How to Use Buttons, Check Boxes, and Radio Buttons tutorial.

提交回复
热议问题