Java - Handle multiple events with one function?

10,637

Solution 1

The object that sent the event is the event source so evt.getSource() will get you that. However, it would be far better to have separate handlers for separate events.

Solution 2

Call the getSource() method of the ActionEvent. For example:

public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    // 'source' now contains the object clicked on.
}

Solution 3

Handle multiple button presses with one function(method) only if all those button presses do exactly the same thing.

Even in that case have a private method and call this private method from all the places wherever needed.

It is not difficult to write separate event handlers for different buttons. In the simplest case, write anonymous handlers, as follows:

aButton.addActionListener(new java.awt.event.ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            myMethod();
        }
    });

In a more complex scenario, write a separate class that extends ActionListener and use that inside the addActionListener() call above.

This is not difficult, easy to maintain and extend, and way better than single actionPerformed for everything.

(In NetBeans, right click on the button(s), Events->Action->actionPerformed, the code is generated for you)

Share:
10,637
Logan Serman
Author by

Logan Serman

Updated on June 05, 2022

Comments

  • Logan Serman
    Logan Serman almost 2 years

    First of all, I am a complete Java NOOB.

    I want to handle multiple button presses with one function, and do certain things depending on which button was clicked. I am using Netbeans, and I added an event with a binding function. That function is sent an ActionEvent by default.

    How do I get the object that was clicked in order to trigger the binding function from within that function so I know which functionality to pursue?