JPanel Action Listener

Ronin picture Ronin · Nov 21, 2013 · Viewed 31.7k times · Source

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 I need is a listener on the the whole JPanel looking for events, whenever anything changes. I believe I need an action listener but I can't find anything to bridge the action Listener with the JPanel

JPanel Window = new JPanel();
Window.addActionListener(new ActionListener(){
//Check if configurations is good
}

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.

Answer

dic19 picture dic19 · Nov 21, 2013

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.