Event listener with one method calling – Java Basics #36

One methodĀ event listener calling

In last article I taught you how to handle event listeners. Let’s take a closer look at a code that has been used in example:

I used a nested class here. However simple listeners may be created within one line. By simple I mean listeners that call one method or perform one action, as in example above.

EventHandler is a class that may be used for this task:

So, in create() method we must pass some parameters. ActionListener.class is first. Then, we need to pass our frame object. In my case it’s gui. Next, pass the method name, as a string.

You probably noticed, that the original code has label parameter. We need to tell EventHandler about this as well. If you pass one parameter to your method, you can just add another string to parameter:

Second parameter needs to be public. Otherwise, Java won’t be able to find it.