gpt4 book ai didi

Java - 如何调整 GroupLayout 中的组件大小

转载 作者:行者123 更新时间:2023-12-01 06:20:23 36 4
gpt4 key购买 nike

我的 GroupLayout 有问题。我的代码是:

public chat () {

JTextField chatbox;
JTextField msgbox;
JButton sendbutton;
GroupLayout layout;

super();
chatbox = new JTextField();
msgbox = new JTextField();
sendbutton = new JButton("Send");
layout = new GroupLayout(this);

sendbutton.setPreferredSize(new Dimension(60, 20));

setBackground(new Color(255, 255, 255));

setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(chatbox)
.addGroup(layout.createSequentialGroup()
.addComponent(msgbox)
.addComponent(sendbutton))
);

layout.linkSize(SwingConstants.HORIZONTAL, sendbutton);

layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(chatbox)
.addGroup(layout.createParallelGroup()
.addComponent(msgbox)
.addComponent(sendbutton))
);
}

问题是布局中的组件尽可能大。我无法限制这个尺寸。问题是,如何设置项目的恒定高度?

或者从另一方面来说,当窗口大小调整时会调用哪个函数?我可以重写该函数,即父 JPanel 的 getSize (在 JPanel 中),然后根据百分比设置大小吗?你觉得怎么样?

//问题已解决。

从底部开始第五行发生变化

.addGroup(layout.createParallelGroup()

对于

.addGroup(layout.createParallelGroup(BASELINE)

谢谢大家的帮助。

最佳答案

我添加这个是因为乍一看答案并不那么清楚,尽管它确实很好地回答了我自己的这个问题版本:-)

基本上,在 GroupLayout 中创建垂直组时,如果您希望组件处于其首选高度(大多数情况下),则可以添加参数 GroupLayout.Alignment.BASELINE。

我会解释 BASELINE 参数,但 Oracle 文档 ( http://docs.oracle.com/javase/7/docs/api/javax/swing/GroupLayout.ParallelGroup.html ) 做得更好:

The baseline is calculated based on the preferred height of each of the elements that have a baseline. The baseline is calculated using the following algorithm: max(maxNonBaselineHeight, maxAscent + maxDescent), where the maxNonBaselineHeight is the maximum height of all elements that do not have a baseline, or are not aligned along the baseline.

正如其他人所说,不应使用 setMaximumSize(),我建议查看 the link @kleopatra 提到了更多信息。

顺便说一句,问题末尾的代码似乎并不完全正确(至少当我尝试类似的东西时)。据我所知,从底部算起的第五行应该是

.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)

而不是

.addGroup(layout.createParallelGroup(BASELINE)

关于Java - 如何调整 GroupLayout 中的组件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9471056/

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