2

我的目标是让我的组件根据我的 GridBagConstraints 调整大小,但由于某种原因,当我的小程序运行时,组件会出现,但不会像我预期的那样填满整个小程序。这是我的代码:

服务器面板:

public class ServerPanel extends JPanel{
    public ServerPanel(){
    setLayout(new GridBagLayout()); //use gridbag layout
    GridBagConstraints gbc = new GridBagConstraints();

    JButton reverse = new JButton("Reverse text");
    JButton send = new JButton("Send text");
    JButton clear = new JButton("Clear text");
    JTextField text = new JTextField("Test");
    JScrollPane scrollPane = new JScrollPane(text, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    //Reverse button
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = gbc.HORIZONTAL;
    add(reverse, gbc);

    //send button
    gbc.gridy = 1;
    add(send, gbc);

    //clear button
    gbc.gridy = 2;
    add(clear,gbc);

    //text field
    gbc.gridy = 3;
    gbc.ipadx = 20;
    gbc.ipady = 20;
    gbc.fill = gbc.BOTH;
    add(scrollPane, gbc);
    }

}

扩展 JApplet 的 ServerApplet 的相关代码:

public void init(){
        //dim = getSize();
        //create the GUI in the EDT
        SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            //System.out.println(dim);
            setLayout(new BorderLayout());
            add(new ServerPanel(), BorderLayout.CENTER);

        }
    });
}

发生的情况是创建了正确的组件,并且面板在小程序中居中,但它不会扩展以填充整个小程序。任何帮助表示赞赏。谢谢!

4

1 回答 1

3

当我看到这个:

但由于某种原因,当我的小程序运行时,组件出现了,但没有像我预期的那样填满整个小程序......

与 GridBagLayout 一起使用时,我查看是否在 GridBagConstraints 上设置了 weightx 和 weighty 字段,因为它们被保留为默认值 0 的症状是组件都聚集在中心。

解决方案:在需要的地方和时间设置这些字段。如果一个组件应该在 x 方向上扩展,那么给它一个 + weightx,也许是 1.0,对于 weighty 也是如此。

于 2012-12-01T23:09:05.533 回答