简体   繁体   中英

Instanceof, Enum Or Multiple Listeners for JButtons

On my swing GUI I have lines of data and a number of buttons, the user selects a number of items and then then selects a button.

Each button applies a different rule to the data and so different functions need to be called for every button, I'm using an MVC design pattern and my question is such, How should I handle the different needs of every button?

  1. Create a class 'MyButton' which extends JButton then give this some sort of Enum, I can then create 1 action listener and then check which button has been pressed in the ActionListener by inspecting the Enum.

  2. Similar to above but with a different class for each button then using instanceof to determine which has been pressed.

  3. Implement a separate ActionListener for each button

  4. Other?

Which is the best method to use if any? Any advice would be greatly received!

Implement a separate listener for each button.

First because it's the usual solution. Second, between there's no reason to extend JButton just to do something else when it's clicked. That's the role of the ActionListener. Swing components are designed to be used as is, and you should generally not extend them.

It's MVC: you separate the logic (in Actions) and the view (the button).

There is no need to use an enum or to subclass JButton. What you can do to keep things clean when you have dozens of buttons, is a factory class to create Action instances.

If I get your question correctly, you mean to say, you have a data in line items and every line items have a button, which when pressed invokes a rule pertaining to the line item.

If so, then

  • If you take the 2nd approach, you need to code inside your action listener every time a new line item added in future.
  • Third approach will also have same implication as above

First approach sounds quite good. You can have a Factory which may have a hashmap keyed with the enum variables and the respective rule. Inside the action listener get the rule from the factory and invoke it.

This way you get a proper separation of concerns and your action listener will act as a controller, having no knowledge of rules and data items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM