gpt4 book ai didi

java - GroupLayout:组件未按预期布局?

转载 作者:行者123 更新时间:2023-11-30 04:05:22 24 4
gpt4 key购买 nike

组件应该这样布局:

(A)
+--------------------+
|标签1 文本字段1 |
|标签2文本字段2 |
|标签3 文本字段3 |
+--------------------+

但是它们现在的样子是:

(B)
+------------------------------------------------ --------+
|标签1 标签2 标签3 文本字段1 文本字段2 文本字段3 |
+------------------------------------------------ --------+

如何使它们看起来像 (A)

SSCCE代码:

import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class GroupLayoutTest extends JPanel
{

GroupLayout layout;
JTextField tf_id;
JTextField tf_name;
JTextField tf_price;
JLabel lb_id;
JLabel lb_name;
JLabel lb_price;

public GroupLayoutTest()
{
layout = new GroupLayout(this);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

lb_id = new JLabel("id");
lb_name = new JLabel("name");
lb_price = new JLabel("price");

tf_id = new JTextField(5);
tf_name = new JTextField(5);
tf_price = new JTextField(5);
createGUI();
}

private void createGUI()
{
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lb_id)
.addComponent(lb_name)
.addComponent(lb_price))
.addGroup(layout.createParallelGroup()
.addComponent(tf_id)
.addComponent(tf_name)
.addComponent(tf_price))
);

layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lb_id)
.addComponent(tf_id))
.addGroup(layout.createParallelGroup()
.addComponent(lb_name)
.addComponent(tf_name))
.addGroup(layout.createParallelGroup()
.addComponent(lb_price)
.addComponent(tf_price)
));
}

@Override
public Dimension getPreferredSize()
{
return new Dimension(400, 500);
}

public void creatAndShowGUI()
{
JFrame frame = new JFrame();
frame.add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{

@Override
public void run()
{
GroupLayoutTest test = new GroupLayoutTest();
test.creatAndShowGUI();
}
});
}

}

最佳答案

您正确设置了布局,但忘记将其添加到面板中。因此,在代码中的某处添加 this.setLayout(layout); 行,它应该可以工作。

关于java - GroupLayout:组件未按预期布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20910216/

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