Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add an ActionListener onto a JButton in Java

private JButton jBtnDrawCircle = new JButton("Circle"); private JButton jBtnDrawSquare = new JButton("Square"); private JButton jBtnDrawTriangle = new JButton("Triangle"); private JButton jBtnSelection = new JButton("Selection"); 

How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?

like image 249
user37037 Avatar asked Nov 12 '08 18:11

user37037


People also ask

Can you add ActionListener to JPanel?

So you can't attach an ActionListener to a JPanel .


1 Answers

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() {    public void actionPerformed(ActionEvent e) {      selectionButtonPressed();   }  } );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:

jBtnSelection.addActionListener(e -> selectionButtonPressed()); 

In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).

The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

like image 107
David Koelle Avatar answered Oct 05 '22 00:10

David Koelle