开发者

Passing arguments with a method in it. Java

Could you please explain what this approach of passing such an argument to the addActionListener method is? I understand that button variable of a JButton type is created and event listener is defined. It's not really clear for me the addActionListener argument, namely actionPerformed method definition in it. Where can I ready about such an approach?开发者_StackOverflow中文版 Thanks.

JButton button = new JButton("New button");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        System.out.println("Hello");
    }
});


What is happening here is that addActionListener takes an object that implements ActionListener as a parameter.

You are creating an anonymous class that implements the ActionListener interface and within it defining the method actionPerformed which is required by the ActionListener interface.

This anonymous class gets instantiated as an object and that object is passed into the addActionListener method.


On the button.addActionListener(), the implemented class is called an anonymous inner class. This class only exists within your addActionListener() method, and it's not known to anyone else. Basically, you are creating an ActionListener (even though it's an interface) that's passed to the addActionListener().

Since ActionListener is an interface, you will have to implement the actionPerformed() method. When an event happens to your JButton, the listener in your JButton is informed (through the actionPerformed() method) passing the event that occurred, ActionEvent. Just a further (extra) note From Wikipedia:

Anonymous inner classes are also used where the event handling code is only used by one component and therefore does not need a named reference.

This avoids a large monolithic actionPerformed(ActionEvent) method with multiple if-else branches to identify the source of the event. This type of code is often considered messy and the inner class variations are considered to be better in all regards.

This is basically an Observer Pattern (just an extra bonus answer).


To answer your question literally, you can pass a method as an argument.

Method method = clazz.getMethod("method-name", method-parameter.class);
yourObject.call(method);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜