Chapter 7: Problem 8
How do you register an event listener with a JButton component?
Short Answer
Expert verified
1. Import necessary libraries, including JButton, ActionListener, and ActionListener event, using the following import statements:
```java
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
```
2. Create a JButton component by instantiating a JButton object and setting its properties, such as text and size:
```java
JButton myButton = new JButton("Click me!");
myButton.setBounds(50, 50, 100, 40);
```
3. Create an ActionListener class that implements the ActionListener interface to define the functionality executed when the JButton is clicked:
```java
class MyButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
}
```
4. Register the ActionListener class with the JButton component by calling the addButtonListener() method and passing an instance of the ActionListener class as an argument:
```java
myButton.addActionListener(new MyButtonListener());
```
After completing these steps, the JButton component will react to click events by executing the actionPerformed() method of the ActionListener class.