gpt4 book ai didi

java - GridBagLayout - 意外添加/和更改间距

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:45 24 4
gpt4 key购买 nike

所以,当我添加面板时,我对面板之间的间距变化(包含 JTextAreas )有疑问,请参阅此 picture 。 :D

示例

第一次按下按钮时addTextArea()叫做。图中状态1 -> 状态2。问题是 panel_buttons 与新添加的 WorkDescription 不太接近(JTextArea)。当多次按下按钮时,它们之间的间距会发生变化。

按钮之前发生了很大的跳跃,但是; c.weighty = 0.1 - 0.3跳跃较小。

// The panel is placed in the center of a JFrame (BorderLayout)
public CONSTRUCTOR {

JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// ...
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.gridheight = 1;
// this is how everything looks at (first pic) start.
panel.add(panel_buttons, c); // panel_buttons is at the right place
}

添加新WorkDescription的方法,即JTextArea :

public void addTextArea() {

WorkDescription wd = new WorkDescription(); //WorkDescription extends JPanel

panel.remove(panel_buttons);
c.weighty = 0.25; // I've messed around with the weighty alot.
// 0.2-0.25 makes the panel_buttons do the least amout of 'down-jump'
panel.add(wd, c);

if(c.gridy < 3 ) {
c.gridy ++;
c.weighty = 1;

panel.add(panel_buttons, c);
}
panel.revalidate();
panel.repaint();
}

最佳答案

我发现的最好的解决方案是,

GridBagLayout 切换到 GridLayout

private JPanel panel_Center = new JPanel(new GridLayout(5,1)); 

然后,当然,删除所有 GridBagConstraints

public void addTextArea() {

WorkDescription wd = new WorkDescription();

panel.remove(panel_buttons);
panel.add(wd);

if(addedWorks < 4 ) {

addedWorks++;
panel.add(panel_buttons);

}

panel.revalidate();
panel.repaint();
}

关于java - GridBagLayout - 意外添加/和更改间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54511939/

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