无法使用borderlayout很好地安排我的元素

时间:2013-05-08 11:01:34

标签: java eclipse swing border-layout

我尝试使用Borderlayout来命令我的元素,因为Gridlayout使所有内容都相同。

我看到的是: what i see 在手动调整大小时,我可以拥有以下内容 what I want to see

这是我的代码的一部分

public InputPanel() {

    tfield = new TextField("Search your terms here!");
    add(tfield, BorderLayout.PAGE_START);

    searchButton = new JButton("Search");
    searchButton.addActionListener(this);
    add(searchButton, BorderLayout.LINE_START);

    clearButton = new JButton("Clear Text");
    clearButton.addActionListener(this);
    add(clearButton, BorderLayout.LINE_END);

    resultsArea = new TextArea();
    add(resultsArea, BorderLayout.PAGE_END);
}

似乎它没有帮助安排。就像我使用FlowLayout一样。

如何正确格式化?

2 个答案:

答案 0 :(得分:1)

似乎你错过了GridBagLayout,这是真正灵活的布局管理器的首选。使用BorderLayout,你也可以实现很多,但只有很多级别的嵌套,而构建它的代码是非常难以管理的。

答案 1 :(得分:1)

对于BorderLayout,您应该使用NORTH,SOUTH,EAST,WEST和CENTER来放置组件。要实现上述布局,您应该创建一个具有FLOWLAYOUT的面板,您可以在其中添加文本字段,seachbutton和clear按钮。然后将该面板放在BorderLayout.NORTH内。在此之后,将JTextArea放在BorderLayout.NORTH

public InputPanel() {

    JPanel topPanel = new JPanel(); // Create a new panel
    topPanel.setLayout(FlowLayout()); //Left to right alignment is default for FlowLayout

    //Add your textfield and buttons to the panel with flowlayout
    tfield = new TextField("Search your terms here!");  
    topPanel.add(tfield);

    searchButton = new JButton("Search");
    searchButton.addActionListener(this);
    topPanel.add(searchButton);

    clearButton = new JButton("Clear Text");
    clearButton.addActionListener(this);
    topPanel.add(clearButton);

    add(topPanel, BorderLayout.NORTH); // Add the panel containing the buttons and textfield in the north

    resultsArea = new TextArea();
    add(resultsArea, BorderLayout.CENTER); //Add the textarea in the Center

}

这给了我以下的外观: enter image description here