gpt4 book ai didi

java - 展开 JFrame 后如何固定 JPanel 的位置

转载 作者:行者123 更新时间:2023-11-30 01:57:22 25 4
gpt4 key购买 nike

我正在尝试使用 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:");
}

}

以下是展开框架之前和之后程序的外观。

之前:

enter image description here

之后:

enter image description here

因此,即使在扩展框架之后,我也希望程序将这 3 个 JPanel 留在容器的中间。

谢谢!

最佳答案

您可以设置gridLayout并将这些元素放入其中。

JPanel jp = new JPanel();
GridLayout gl = new GridLayout(3,4); //3 rows, 4 columns
jp.setLayout(gl);

完成此操作后,只需按顺序将元素放入布局内即可。

jp.add(label1);
jp.add(button1);
//etc...

关于java - 展开 JFrame 后如何固定 JPanel 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com