用swing实现一个窗口,上面是一行文字下面三个按钮,文本需要在上面,三个按钮在文本下面,给出代码
时间: 2024-02-17 11:01:40 浏览: 28
以下是使用Swing实现一个窗口,包含一行文本和三个按钮的代码:
```java
import javax.swing.*;
public class MyWindow extends JFrame {
public MyWindow(String title) {
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建一个面板
JPanel panel = new JPanel();
// 创建一行文本
JLabel label = new JLabel("这是一行文本");
// 创建三个按钮
JButton button1 = new JButton("按钮1");
JButton button2 = new JButton("按钮2");
JButton button3 = new JButton("按钮3");
// 将文本添加到面板上
panel.add(label);
// 创建一个新的面板,用于放置三个按钮
JPanel buttonPanel = new JPanel();
// 将三个按钮添加到新的面板上
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
// 将新的面板添加到原来的面板上
panel.add(buttonPanel);
// 将面板添加到窗口上
getContentPane().add(panel);
// 设置窗口大小并显示
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args) {
new MyWindow("Swing窗口");
}
}
```
运行该代码,将会弹出一个包含一行文本和三个按钮的窗口,其中文本在上面,三个按钮在文本下面。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)