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:
JButton jBtnSelection = new JButton("Selection");
jBtnSelection.addActionListener(this);
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:
jBtnSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
2. Updated (Java 8 Lambda Expressions):
Using lambda expressions introduced in Java 8, you can simplify the anonymous inner class approach:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
This lambda expression directly calls the selectionButtonPressed() method when the button is clicked, avoiding the need for an anonymous inner class.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3