Method of adding ActionListener

Let's say I have a button named button1. If I want to create an actionListener for the button I have to select: (In the second you have to extend the ActionListener interface)

// Imports public class Test{ JButton test = new JButton(); Test(){ // Pretend there is an adapter test.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ ... } }); ... } 

or

 // Imports public class Test2 extends ActionListener{ JButton button2 = new JButton(); Test2(){ button2.addActionListener(this); } // Pretend there is an adapter public void actionPerformed(ActionEvent e){ Object src = e.getSource(); if(src == button2){ ... }else{ ... } } 
+4
source share
3 answers

In the second case, you need to implement the ActionListener interface. Other than that, the answer is "it depends." If it makes sense to reuse the same action listener for multiple graphics components, use the second version. If event processing is a one-time task for one component, use the first version.

+3
source

Go for the first one. You should not have GUI classes that implement your listeners as well, since this requires too much from the GUI or view class. Having separated your listener code, even if it is in an anonymous listener class, it will be easier for you to do this later if you want to completely separate your listener code from the view code.

+3
source

If each listener is unique, you probably want to use anonymous classes (first example). If you would otherwise have to rewrite the same code over and over, then implementing it in a named class (as in the second example) would be preferable, so you can just reuse the same listener.

However, instead of extending the ActionListener (as in your second example), you will probably find that including a listener implementation in another class (even an inner class that implements ActionListener) provides a better logical separation of your code.

+1
source

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


All Articles