gpt4 book ai didi

java - GroupLayout - 简单的组件定位

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

我一直在使用 GridBagLayout,但最近转向了 GroupLayout。下面是我拥有的和我需要的屏幕截图。然后是代码。

我需要改变什么?

我有什么

enter image description here

我需要什么

enter image description here

我认为我应该使用 TRAILINGLEADING 常量,但 GUI 没有响应。这可能是大多数人建议人们避免使用 GroupLayout 的原因吗?我之前一直用的是GridBagLayout,比较复杂,而GroupLayout代码看起来简单很多。这就是我使用它的原因。下面给出了我的代码,我需要什么才能达到预期的效果?

public class GroupLayoutOne extends JFrame{

JLabel lbText = new JLabel("Text one");
JTextField txText = new JTextField();
JLabel lbText2 = new JLabel("Text two");
JTextField txText2 = new JTextField();
JPanel pnCompo = new JPanel();

public static void main(String[] args) {

GroupLayoutOne glx = new GroupLayoutOne();
glx.init();
glx.setVisible(true);
glx.setSize(new Dimension(400,200));
glx.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

void init(){
GroupLayout gl = new GroupLayout(getContentPane());
this.getContentPane().setLayout(gl);

pnCompo.setPreferredSize(new Dimension(300,300));
pnCompo.setBorder(BorderFactory.createTitledBorder("More Components"));
gl.setHorizontalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(lbText2)
.addComponent(pnCompo)
)
.addGroup(gl.createParallelGroup()
.addComponent(txText)
.addComponent(txText2)

)
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(txText)

)
.addGroup(gl.createParallelGroup()
.addComponent(lbText2)
.addComponent(txText2)

)
.addComponent(pnCompo)
);
pack();
}
}

最佳答案

将您的 init 方法替换为以下代码:BTW:使用 NetBeans 或 Eclipse 绘制 swing UI。这比自己编写代码要容易得多。

    GroupLayout gl = new GroupLayout(getContentPane());
this.getContentPane().setLayout(gl);

pnCompo.setPreferredSize(new Dimension(300,300));
pnCompo.setBorder(BorderFactory.createTitledBorder("More Components"));
gl.setHorizontalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addGroup(gl.createSequentialGroup().addComponent(lbText)
.addComponent(txText))

.addGroup(gl.createParallelGroup()
.addGroup(gl.createSequentialGroup().addComponent(lbText2)
.addComponent(txText2))

.addComponent(pnCompo))
)
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(txText))
.addGroup(gl.createParallelGroup().addComponent(lbText2)
.addComponent(txText2)
)
.addComponent(pnCompo)
);
pack();

关于java - GroupLayout - 简单的组件定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52311915/

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