thestudent
thestudent

Reputation: 1

How to implement an action listener with generic enums?

I am in the process of refactoring my application and my teacher recommended that I replace the GUI builder generated code with a more generic one.

Right now every JMenuItem has its own action listener. What I'm trying to achieve is a sort of generic control function for every menu item by using enums in a single action listener. The code below should give you a general idea. clE is the enum key and I believe the enum should implement an interface for reading its label.

I've been doing a bit of research and I'm sure it's something simple, but I can't get fully grasp it yet. Thanks in advance!

public class JECheckBox<E extends ENUM_Label_INTF<?>> extends JCheckBox {

     private final E clE;

     // +++++++ CONSTRUCTOR +++++++++
     public JECheckBox(final E clE) {
         super( ((GetLabelINTF) clE).GetLabel() );
         this.clE = clE;
     }

     public E GetKey() {
         return clE;
     }
}

Upvotes: 0

Views: 278

Answers (2)

camickr
camickr

Reputation: 324147

I believe the enum should implement an interface for reading its label.

If you want to read the text of the check box, then you create a generic listener by doing something like:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JCheckBox checkbox = (JCheckBox)e.getSource();
        System.out.println( checkbox.getText() );
    }
};

Now you can add the Action to each check box.

Note an Action is a more versatile ActionListener. Read the section from the Swing tutorial on How to Use Actions for more information and examples.

Upvotes: 1

Ray Tayek
Ray Tayek

Reputation: 10003

Not suew what you mean by generic enums. Try giving every menu item (or any component) it's own name using component.setName(SomeEnum.soneValue.toString()). Then get the name in the action listener and do a switch(SomeEnum.valueOf(name).

Upvotes: 0

Related Questions