Handle multiple events with a single function?

First of all, I am full Java NOOB.

I want to handle multiple button presses with one function and do certain things depending on which button was pressed. I am using Netbeans and I have added an event with a binding function. This function dispatches an ActionEvent by default.

How to get the object that was pressed to call the binding function inside this function so that I know what functions should be performed?

+1
source share
4 answers

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

+7

getSource() ActionEvent. :

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

(), .

, .

. :

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

, ActionListener addActionListener() .

, , , actionPerformed .

( NetBeans, , - > Action- > actionPerformed, )

+1

If you use AWT events, the ActionEvent supports the getSource () method, which will give you the object that supposedly generated the event.

Moreover, there are better projects in which each object creates its own event handler

0
source

All Articles