How to listen to custom actions

I am new to Swing and need some help with action listeners. I saw how they were used in this example:

button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Do something } }); 

However, I want to do something more:

 button.addActionListener(myFunc); public void myFunc(ActionEvent e) { // Do something } 

Is it possible?

+4
source share
5 answers

Two possible approaches are possible here: either you can simply call your myFunc method directly from the first example you give:

 button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myFunc(e); } }); 

... Or you can define an inner class that implements the actionlistener, and then use it:

 class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { //Your code } } button.addActionListener(new MyActionListener()); 

On a futuristic note, when Java 8 hits the shelves (2013, so don't hold your breath), you can do it more briefly using closure.

+7
source

If you want to avoid extra classes, you can use the trampoline reflective class. I wrote a utility class for this:

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/action/ReflectiveXAction.html

Learn more about reflexive actions: Chapter 6.2.3, page 73 of the Java book "Strategies and Tactics of the Java Platform" by Steve Wilson and Jeff Kesselman.

Textbook:

http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/action/index.html

Maven:

 <dependency> <groupId>org.softsmithy.lib</groupId> <artifactId>lib-core</artifactId> <version>0.1</version> </dependency> 

Download:

http://sourceforge.net/projects/softsmithy/files/softsmithy/v0.1/

+4
source

Pretty simple:

 button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myFunc(e); } }); public void myFunc(ActionEvent e) { // Do something } 

... I know this is a little boilerplate ... but java does not support the transfer function as parameters.

+3
source

Perhaps only if the method returned an ActionListener , otherwise not. Of course, it is fully valid for delegating ActionEvent processing ActionEvent separate method.

+3
source

If you want to use Java 8 lambda expression

 button.addActionListener(ae -> myFunc(ae)); 

Or, as an alternative to the other answers, for lower versions of Java you can use an anonymous class.

  ActionListener myFunc = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //code } }; button.addActionListener(myFunc); 
+1
source

All Articles