Jason SangMin Park
Jason SangMin Park

Reputation: 11

adding new JButton() with actionListener without declaring it

I wanted to add a JButton with actionListener to a JPanel without declaring the JButton like below.

JPanel tempPanel = new JPanel();
tempPanel.add(new JButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // DO SOMETHING
        }
   }));

Error message gives me Cannot resolve method 'add(void)'.

I am not sure why this is incorrect. Is it just a grammar error? or is it not possible for me to add JButton with ActionListener like this?

I know for sure, it would work if I do like this.

JButton tempButton = new JButton();
tempButton.addActionListener(new ActionListener() {
    @Override
        public void actionPerformed(ActionEvent e) {
            // DO SOMETHING
        }
    });
tempPanel.add(tempButton);

I will appreciate your help. Thanks in advance.

Upvotes: 1

Views: 354

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

JButton#addActionListener returns void, been the last call in the chain, it's the result that the compiler will try to send to JPanel#add, which, obviously, makes no sense.

While I won't argue the merits of method chaining, the API is the way it is.

You could do something like...

JPanel tempPanel = new JPanel();
tempPanel.add(new JButton(new AbstractAction() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        //...
    }
}));

instead, which would result in the same thing as you're trying to do

Upvotes: 2

Weizhou He
Weizhou He

Reputation: 222

Java give you the error message because the tempPanel.add() takes the return value of addActionListener(), which is void.

Some libraries do provide chained function(eg. Dialog in android) which you can write code like this. But, I'm afraid, in this case, you have to declare it first and then add a listener for the JButton. Or, you could try to write your own Button class which extends JButton, and you can add a parameter as listener in its constructor.

Upvotes: 1

Related Questions