用java swing的3个按钮添加新功能
时间: 2024-03-11 20:47:43 浏览: 64
可以使用Java Swing中的JButton类来创建按钮,然后添加ActionListener来实现按钮的新功能。以下是一个例子:
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonExample extends JFrame implements ActionListener {
private JButton button1, button2, button3;
public ButtonExample() {
setTitle("Button Example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
button1 = new JButton("Button 1");
button1.addActionListener(this); // 添加ActionListener
panel.add(button1);
button2 = new JButton("Button 2");
button2.addActionListener(this); // 添加ActionListener
panel.add(button2);
button3 = new JButton("Button 3");
button3.addActionListener(this); // 添加ActionListener
panel.add(button3);
add(panel);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) { // 判断是哪个按钮被点击了
// 实现按钮1的新功能
System.out.println("Button 1 clicked!");
} else if (e.getSource() == button2) {
// 实现按钮2的新功能
System.out.println("Button 2 clicked!");
} else if (e.getSource() == button3) {
// 实现按钮3的新功能
System.out.println("Button 3 clicked!");
}
}
public static void main(String[] args) {
ButtonExample example = new ButtonExample();
example.setVisible(true);
}
}
```
这个例子创建了一个JFrame窗口,其中包含了3个JButton按钮。每个按钮都添加了一个ActionListener,当用户点击按钮时,ActionListener会触发相应的事件,实现按钮的新功能。在这个例子中,当用户点击任何一个按钮时,控制台会输出相应的信息。你可以根据实际需求来实现你自己的新功能。
阅读全文
相关推荐


















