【发布时间】:2019-06-27 22:41:37
【问题描述】:
所以,当我添加面板时,面板之间的间距更改(包含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();
}
【问题讨论】:
-
我对 StackOverFlow 还很陌生,并且对此进行编程.. 问题清楚了吗? :)
-
请编辑问题并将其设为minimal reproducible example。
-
我现在更新了 :D
-
布局约束(例如
GridBagConstraints)并不意味着是“动态的”(至少 90% 的时间)。因此,请避免在程序逻辑中使用它们。使用它们来构建“静态”用户界面。 -
1) “我现在更新了” 好的,但请注意,现在的问题仍然没有您当前尝试的minimal reproducible example。如果我们不能在绝对没有更改的情况下复制/粘贴编译/运行,则它不是 MCVE。 2) GUI 通常是通过组合用户所看到的 1 GUI 的不同部分中的布局来实现的。与 GUI 的该部分相关的每个布局。没有“最佳布局”,只有“工作的最佳布局”。 3) 以最小尺寸提供 ASCII 艺术或 GUI 的 预期 布局的简单绘图,如果可调整大小,则具有更大的宽度和高度 - 以显示应如何使用额外空间。
标签: java swing awt layout-manager gridbaglayout