如何在使用GridBagLayout时阻止TextArea“捕捉”到不同的大小

时间:2014-12-18 03:32:24

标签: java textarea gridbaglayout

我正在尝试了解GridBagLayout,并且我已经让我的TextArea组件按照我想要的方式运行,除非窗口垂直重新调整大小。

当窗口重新调整为更短时,底部TextArea会捕捉到更大的尺寸,而不是保持当前尺寸,并在房间用完时根据重量缩小。

我觉得这很简单,比如改变填充或其他东西,但我无法理解......

代码:

public class Window {

    Frame frame;
    Panel panel;
    TextArea top;
    TextArea bottom;
    GridBagConstraints topC, bottomC;

    Window(){
        createWindow();
    }


    public static void main(String[] args){
        new Window();
    }


    private void createWindow(){
        //create panel for text areas
        panel = new Panel(new GridBagLayout());

        //create top text area
        top = new TextArea();
        top.setPreferredSize(new Dimension(500,500));

        //create bottom text area
        bottom = new TextArea();
        bottom.setPreferredSize(new Dimension(500,75));

        //set constraints for top text area
        topC = new GridBagConstraints();
        topC.anchor = GridBagConstraints.NORTH;
        topC.fill = GridBagConstraints.BOTH;
        topC.gridheight = GridBagConstraints.RELATIVE;
        topC.gridwidth = GridBagConstraints.REMAINDER;
        topC.gridx = 0;
        topC.gridy = 0;
        topC.insets = new Insets(2,2,2,2);
        topC.weightx = 1.0;
        topC.weighty = 1.0;

        //set constraints for bottom text area
        bottomC = new GridBagConstraints();
        bottomC.anchor = GridBagConstraints.SOUTH;
        bottomC.fill = GridBagConstraints.BOTH;
        bottomC.gridheight = GridBagConstraints.REMAINDER;
        bottomC.gridwidth = GridBagConstraints.REMAINDER;
        bottomC.gridx = 0;
        bottomC.gridy = 1;
        bottomC.insets = new Insets(2,2,2,2);
        bottomC.weightx = 1.0;
        bottomC.weighty = 0.5;

        //add text areas to the panel
        panel.add(top, topC);
        panel.add(bottom, bottomC);

        //create frame
        frame = new JFrame();
        frame.setTitle("Client Console");
        frame.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                frame.dispose();
            }
        });
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

}

1 个答案:

答案 0 :(得分:1)

将文字区域放在scroll pane中。

您可能还想看看Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

你真的需要使用AWT吗?它已经过时了(比如15年过时了)。如果你可以考虑使用Swing或JavaFX ......