button对应的监听器
时间: 2024-02-16 16:59:58 浏览: 30
在Java中,通常使用ActionListener接口对按钮进行监听。可以通过实现ActionListener接口并重写actionPerformed()方法来处理按钮被点击的事件。代码示例如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo implements ActionListener {
JFrame frame;
JButton button;
public ButtonDemo() {
frame = new JFrame("Button Demo");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Click me!");
button.addActionListener(this);
frame.add(button);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("Button clicked!");
}
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
在上面的示例中,我们创建了一个JFrame窗口和一个JButton按钮,然后将按钮添加到窗口中。通过调用addActionListener()方法并传入实现了ActionListener接口的对象,我们可以监听按钮的点击事件。在actionPerformed()方法中,我们可以编写处理按钮点击事件的代码。
相关推荐
![](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)