Best practice for gui and actionlistener

I would know what works best for running actionenerener in java? for example, in my class a this is my gui (design), then class b will be my executor of actions? or better on one page are they all? thanks.

0
source share
4 answers

It depends. If you want to use an ActionListener for several user interface components: a button, menu item, ... then it would be advisable to do this in a separate class. In addition, if the code inside the actionPerformed method has many lines, it makes sense to do it separately.

Otherwise, if there are not many user interface components in your class, you can define ActionListener as an anonymous implementation and directly attach it to your component.

 button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // ... } }); 
+3
source

I'm not sure what you are asking for, but in general, if my actionListener is small, say a dozen lines or less, I will save it in my class of GUI components as an anonymous implementation.

 button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // ... } }); 

If my actionListener is large, I will make it a separate class.

 public class ButtonListener implements ActionListener { private JPanel panel; public ButtonListener(JPanel panel) { this.panel = panel; } public void actionPerformed(ActionEvent event) { // ... } } 
+3
source

I'm not sure I understand what you are asking for sure. But here's a shot: from a design point of view, it is best for the second class to listen to events triggered by your graphical interfaces (these were your controls).

Lets call this second class Controller. When the controller realizes that something happened on your controls, it will begin to carry out a sequence of tasks (for example, data on the return or sending of information or confirmation of information about your graphical interface, etc.).

So, in terms of interfaces, your controller should be your ActionListener.

+2
source

As Robin pointed out, where possible, you should have an Action API.

It provides autonomous, reusable manipulators that can be applied to multiple components.

They are especially useful if you want to provide the same action in multiple places on the user interface. Think, copy and paste, for example, it would be useful to have this in the main menu, in the pop-up menu and, probably, on the toolbar, which has a lot of repeating code.

Tick How to use Actions for information

+1
source

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


All Articles