What is the difference between a common or individual actionPerfomed method

Please help me understand the difference between adding an action listener to the JComponent in the following two approaches.

First method: implementing an actionListener for my class and adding a generic actionPerformed method that selects an event-based selection

class Test implements ActionListener { JButton jbutton = null; public Test(){ jbutton = new JButton(); jbutton.addActionListener(this); } public void actionPerformed(ActionEvent e){ //Perform operation here; } } 

The second method: defining an action listener for an individual JComponent.

 JButton jbutton = new JButton(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //Perform operation here } }); 

What is the difference between the two approaches and which one is cleaner and easier to maintain, and if there are any performance benefits?

+4
source share
1 answer

I would go with the first approach if:

  • The action is triggered through various events. For example, you have an action that changes the GUI language from English to Arabic (where you need to reinstall the components to lie from right to left), and this action can be launched using some key bindings , for example ( Alt + R ) and JMenuItem , and maybe through some buttons.

  • Several actions have the same base code. For example, a calculator application in which each button of a mathematical operation launches the same action, and based on the action command, you can define the operation from inside actionPerformd() . They share GUI updates.

and I would go with a second approach if:

  • An action is attached to only one event, and you want to record it on the fly.

Whatever I do is something like this:

 public class MainFrame extends JFrame implements ActionListener 

but I would write:

 public class CustomListener implements ActionListener 

See also:

+3
source

Source: https://habr.com/ru/post/1480552/


All Articles