简体   繁体   中英

Java - One ActionListener for multiple JButtons

I'm writing a little Java Application. I have multiple JButtons. The code for each button is exactly the same, thus I want only one ActionListener. But in that ActionListener I need to call "setText()" for the corresponding button, which was clicked. Is that possible? How would I achieve this?

I tried the following:

private void btnClicked(java.awt.event.ActionEvent evt) {
  (JButton)evt.setText("Hello");
}

But that doesn't work - it says "Cannot find symbol".

Thanks in advance;)

(JButton)evt.setText("Hello");

You are not invoking any method on the "evt" object.

You need to invoke the getSource() method to access the button.

I always like to do it the long way so I don't make mistakes:

JButton button = (JButton)evt.getSource();
button.setText( "Hello" );

but the short way would be:

((JButton)evt.getSource()).setText("Hello");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM