Java - Handle multiple events with one function?

爱⌒轻易说出口 提交于 2019-12-13 18:08:09

问题


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?


回答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.




回答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.
}



回答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)




回答4:


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

That being said, there are better designs in which each object instantiates its own event handler



来源:https://stackoverflow.com/questions/501533/java-handle-multiple-events-with-one-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!