的GridBagLayout - 意外增加/改变和间距

问题描述 投票:1回答:1

所以,我有一个面板(含JTextAreas)之间的间距变化的一个问题,当我添加面板,请参阅本picture。 :d

当按下一个按钮,在第一时间addTextArea()被调用。状况1 - >状态2的图片。而问题是,panel_buttons不接近新增WorkDescriptionJTextArea)。而当按钮被按下多次,它们之间的间距变化。

按钮之前做了一个大的跳跃,但是, 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();
}
java swing awt layout-manager gridbaglayout
1个回答
0
投票

我找到了最好的解决办法是,

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();
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.