swing点击按钮界面变更
时间: 2023-07-05 19:21:56 浏览: 56
您可以通过使用ActionListener接口来实现按钮的点击事件。以下是一个示例代码,点击按钮时会将标签文本更改为“按钮被点击了”:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonDemo {
private JFrame frame;
private JLabel label;
public ButtonDemo() {
frame = new JFrame("Button Demo");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton("Click me");
label = new JLabel("Press the button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button clicked");
}
});
panel.add(button);
panel.add(label);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new ButtonDemo();
}
}
```
在这个示例中,我们创建了一个JFrame窗口,并在其中添加了一个JPanel面板,然后在面板上添加了一个JButton按钮和一个JLabel标签。我们通过addActionListener方法将一个ActionListener对象添加到按钮上,当按钮被点击时,actionPerformed方法会被调用,并将标签文本更改为“Button clicked”。
相关推荐
![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)