java 按钮实现代码_实现按钮处理的两种方式 JAVA中怎么实现按钮功能?
时间: 2024-03-18 13:39:53 浏览: 16
Java 中实现按钮功能有两种方式:使用匿名内部类或使用实现 ActionListener 接口的类。
1. 使用匿名内部类实现按钮功能:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Demo");
JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello World!");
}
});
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
```
在这个例子中,我们创建了一个 JFrame、一个 JPanel 和一个 JButton。我们使用匿名内部类实现了 ActionListener 接口的 actionPerformed 方法,当用户点击按钮时,将弹出一个对话框显示 "Hello World!"。
2. 使用实现 ActionListener 接口的类实现按钮功能:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo implements ActionListener {
private JFrame frame;
private JPanel panel;
private JButton button;
public ButtonDemo() {
frame = new JFrame("Button Demo");
panel = new JPanel(new FlowLayout());
button = new JButton("Click Me");
button.addActionListener(this);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello World!");
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
在这个例子中,我们创建了一个类 ButtonDemo 实现了 ActionListener 接口,并实现了 actionPerformed 方法。我们在构造函数中创建了 JFrame、JPanel 和 JButton,并将 ActionListener 设置为 this。当用户点击按钮时,将调用 actionPerformed 方法,弹出一个对话框显示 "Hello World!"。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)