用java写一个既有水平分割又用垂直分割的GUI,且各个面板间有数字1,2,3
时间: 2024-03-10 18:51:15 浏览: 25
好的,我可以为您提供一个简单的Java程序示例,实现一个既有水平分割又有垂直分割的GUI,并在各个面板上显示数字1、2、3。以下是示例代码:
```java
import java.awt.*;
import javax.swing.*;
public class MyGUI extends JFrame {
public MyGUI() {
// 设置窗口大小和位置
setSize(600, 400);
setLocationRelativeTo(null); // 相对于屏幕居中显示
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建水平分割面板
JSplitPane hSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
// 创建左侧面板并添加数字1
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.RED);
JLabel leftLabel = new JLabel("1");
leftPanel.add(leftLabel);
hSplitPane.setLeftComponent(leftPanel);
// 创建右侧垂直分割面板
JSplitPane vSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
hSplitPane.setRightComponent(vSplitPane);
// 创建上方面板并添加数字2
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.GREEN);
JLabel topLabel = new JLabel("2");
topPanel.add(topLabel);
vSplitPane.setTopComponent(topPanel);
// 创建下方面板并添加数字3
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLUE);
JLabel bottomLabel = new JLabel("3");
bottomPanel.add(bottomLabel);
vSplitPane.setBottomComponent(bottomPanel);
// 将水平分割面板添加到窗口中
add(hSplitPane);
// 显示窗口
setVisible(true);
}
public static void main(String[] args) {
new MyGUI();
}
}
```
这个程序创建了一个 `JSplitPane` 水平分割面板,左侧面板设置为红色背景,并在面板上添加数字1,右侧面板是一个垂直分割面板,上方面板设置为绿色背景,并在面板上添加数字2,下方面板设置为蓝色背景,并在面板上添加数字3。最后将水平分割面板添加到窗口中,显示窗口。
运行程序后,您应该可以看到一个既有水平分割又有垂直分割的GUI,各个面板间有数字1、2、3。