如何用内部类的方法给多个按钮添加事件侦听
时间: 2023-12-25 10:03:24 浏览: 31
可以使用内部类来实现多个按钮添加事件侦听的功能,具体步骤如下:
1. 定义一个外部类,该类中包含多个按钮对象。
2. 在外部类中定义一个内部类,该内部类实现 ActionListener 接口,用于处理按钮事件。
3. 在内部类的 actionPerformed 方法中,通过 getSource 方法获取事件源对象,根据事件源对象的不同,执行不同的操作。
4. 在外部类中,为每个按钮对象添加事件侦听器,将内部类的实例作为参数传递给 addActionListener 方法。
示例代码如下:
```
public class ButtonDemo {
private JButton button1;
private JButton button2;
public ButtonDemo() {
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
ButtonListener listener = new ButtonListener();
button1.addActionListener(listener);
button2.addActionListener(listener);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == button1) {
// 处理 Button 1 的事件
} else if (source == button2) {
// 处理 Button 2 的事件
}
}
}
}
```
在上面的示例代码中,ButtonDemo 类中包含两个按钮对象 button1 和 button2,通过内部类 ButtonListener 实现了 ActionListener 接口,用于处理按钮事件。在构造函数中,为每个按钮对象添加事件侦听器,将内部类的实例作为参数传递给 addActionListener 方法。在内部类的 actionPerformed 方法中,通过 getSource 方法获取事件源对象,根据事件源对象的不同,执行不同的操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)