0

I have a JPopupMenu with several JMenuItems inside. Each JMenuItem has it's own ActionListener, but the code looks rather messy having several anonymous inner classes in a row. I've seen some people organize several ActionListeners like this:

public class Foo implements ActionListener {

    private JMenuItem item1, item2;

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == item1) {
            ...
        } else if (e.getSource() == item2) {
            ...
        }
    }

}

While this looks neater, I don't like the idea of having it visible. Are there any better ways of organizing several ActionListeners?

Thanks

Stripies
  • 1,267
  • 5
  • 19
  • 29

1 Answers1

0

This is basically JB Nizet's answer, but make the anonymous action listeners actual classes.

The short ones can remain in the menu class, and the larger ones can be put in their own class. I usually put internal classes towards the bottom of the class. Some people put them all at the top.

By making your action listeners actual classes, you can use a constructor to pass the JComponent instances to the action listener class.

Community
  • 1
  • 1
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111