java 当点击各个按钮会出现对应的画面,代码
时间: 2024-03-02 20:50:23 浏览: 13
好的,以下是一个简单的Java Swing程序示例,它包含3个按钮,点击每个按钮将在窗口中显示不同的文本信息:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JFrame implements ActionListener {
private JButton button1, button2, button3;
private JLabel label;
public ButtonDemo() {
super("Button Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new FlowLayout());
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button3 = new JButton("Button 3");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
add(button1);
add(button2);
add(button3);
label = new JLabel("Click a button to display a message.");
add(label);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
label.setText("You clicked button 1.");
} else if (e.getSource() == button2) {
label.setText("You clicked button 2.");
} else if (e.getSource() == button3) {
label.setText("You clicked button 3.");
}
}
public static void main(String[] args) {
ButtonDemo demo = new ButtonDemo();
demo.setVisible(true);
}
}
```
这个程序创建了一个窗口,其中包含3个按钮和一个标签。当用户单击按钮时,ActionListener接口的actionPerformed方法将被调用,并根据按钮的ID更新标签的文本。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)