猿问

GridBagLayout - 意外添加/更改间距

JTextAreas所以,当我添加面板时,面板(包含)之间的间距发生了变化,请参见这张图片。: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,即a 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();

}


慕森王
浏览 96回答 1
1回答

米脂

我发现的最佳解决方案是,从 切换GridBagLayout到GridLayout。private JPanel panel_Center = new JPanel(new GridLayout(5,1));&nbsp;然后,当然,删除所有GridBagConstraintspublic void addTextArea() {&nbsp; &nbsp; WorkDescription wd = new WorkDescription();&nbsp; &nbsp; panel.remove(panel_buttons);&nbsp;&nbsp; &nbsp; panel.add(wd);&nbsp; &nbsp; if(addedWorks < 4 ) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; addedWorks++;&nbsp; &nbsp; &nbsp; &nbsp; panel.add(panel_buttons);&nbsp; &nbsp; }&nbsp; &nbsp; panel.revalidate();&nbsp; &nbsp; panel.repaint();}
随时随地看视频慕课网APP

相关分类

Java
我要回答