Creating Action Listeners for JButtons in Java
When developing graphical user interfaces (GUIs) in Java, adding action listeners to buttons enables them to respond to user clicks and trigger specific actions within the program. Here's how to implement this functionality using two different methods:
1. Implements ActionListener Interface:
<code class="java">JButton jBtnSelection = new JButton("Selection"); jBtnSelection.addActionListener(this);</code>
2. Anonymous Inner Classes:
For each button, create an anonymous inner class that extends ActionListener and implements the actionPerformed(ActionEvent e) method to handle button clicks:
<code class="java">jBtnSelection.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectionButtonPressed(); } } );</code>
2. Updated (Java 8 Lambda Expressions):
Using lambda expressions introduced in Java 8, you can simplify the anonymous inner class approach:
<code class="java">jBtnSelection.addActionListener(e -> selectionButtonPressed());</code>
This lambda expression directly calls the selectionButtonPressed() method when the button is clicked, avoiding the need for an anonymous inner class.
The above is the detailed content of How to Create Action Listeners for JButtons in Java?. For more information, please follow other related articles on the PHP Chinese website!