java - 展开 JFrame 后如何修复 JPanel 的位置
问题描述
我正在尝试使用 Java Swing 制作程序的界面。我有一个容器,我在其中添加了 3 个 JPanel 和一些组件。问题是当我展开框架时,所有这 3 个 JPanel 都在第一行并排出现。
这是我的代码:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;
public class GraphicRefact extends JFrame {
private Container container;
private JButton button2;
private JButton button1;
private JTextField textField01;
private JLabel label01;
private JButton button03;
private JButton button04;
private JTextField textField03;
private JLabel label03;
private JButton button02;
private JButton button01;
private JTextField textField02;
private JLabel label02;
public static void main(String[] args) {
new GraphicRefact();
}
public GraphicRefact() {
initializeComponents();
setTitle("Title");
setSize(500, 150);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container = new JPanel();
JPanel panel01 = new JPanel();
panel01.add(label01);
panel01.add(textField01);
panel01.add(button2);
panel01.add(button1);
panel01.setBorder(new LineBorder(Color.BLACK, 3));
container.add(panel01);
JPanel panel02 = new JPanel();
panel02.add(label02);
panel02.add(textField02);
panel02.add(button02);
panel02.add(button01);
container.add(panel02);
JPanel panel03 = new JPanel();
panel03.add(label03);
panel03.add(textField03);
panel03.add(button03);
panel03.add(button04);
container.add(panel03);
add(container);
}
private void initializeComponents() {
button1 = new JButton("Open");
button2 = new JButton("Close");
textField01 = new JTextField("Choose the path...");
label01 = new JLabel("Choose File: ");
button01 = new JButton("Button01");
button02 = new JButton("Button02");
textField02 = new JTextField("Choose the path...");
label02 = new JLabel("Choose Dir:");
button03 = new JButton("Button03");
button04 = new JButton("Button03");
textField03 = new JTextField("Choose the path...");
label03 = new JLabel("Choose Dir:");
}
}
这是程序在展开框架之前和之后的样子。
前:
后:
因此,即使在展开框架之后,我也希望程序将这 3 个 JPanel 留在容器的中间。
谢谢!
解决方案
您必须使用正确的LayoutManager。看看那里的例子。BoxLayout 似乎是您想要的。
推荐阅读
- java - MongoDB - 未找到 MongoClientURI ...(使用 maven)
- azure - Device Twin IoT Hub - 从 Python 中的 JSON 获取标签
- php - 如何将特定记录链接到 PHP 表单以更新该记录?
- kubernetes - 在 Kind 上使用 Ingress 和 LoadBalancer 类型的服务
- python - 用于输入自动语音识别模型的不同格式(比特率)的音频数据
- quaternions - 使用带有 gl-matrix.js 的四元数进行简单旋转
- java - Thymeleaf:检索隐藏输入到控制器的值
- python - 如何用while循环解决这个问题
- javascript - 如何避免异步事件处理程序顺序混乱
- java - 如何将视觉添加到 JComponent