在Borderlayout中,Textarea最大化

时间:2014-05-04 17:54:34

标签: java swing layout layout-manager

我有一个简单的问题,但我找不到好的解决方案。我有一个JFrame,其组件位于SOUTHNORTHEASTCENTERCENTER是我的问题。在中心,我有JPanel Borderlayout和2 JTextAreas(一个在NORTH,一个在CENTER)。

我希望第一个面板始终位于面板顶部并将最大值(如果需要)拉伸到面板中间,而不是更多。第二个区域应从第一个区域的末尾开始。如果其中一个文本区域较大,则应显示JScrollPane

实现这一目标的最佳途径是什么?我应该为面板使用其他布局吗?

这是我的小执行示例:

public class myGUI {

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

    public myGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

    //Add Content at South, West and North....
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());
        centerPanel.add(new JScrollPane(new JTextArea("AREA")), BorderLayout.NORTH);
        centerPanel.add(new JScrollPane(new JTextArea("AREA2")), BorderLayout.CENTER);
        frame.add(centerPanel);
        frame.setVisible(true);
    }
}

中心小组的可能情况:

enter image description here

在@Hovercraft Full Of Eels的帮助下解决方案

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

private static GridBagConstraints constraint = new GridBagConstraints();

public MyGUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);

    frame.add(new JLabel("NORTH!"), BorderLayout.NORTH);
    frame.add(new JLabel("EAST!"), BorderLayout.EAST);
    frame.add(new JLabel("SOUTH!"), BorderLayout.SOUTH);

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new GridBagLayout());
    changeConstraint(0,0);

    JTextArea text1 = createTextArea("11111111111111");
    centerPanel.add(text1, constraint);
    changeConstraint(0,1);

    JTextArea text2 = createTextArea("2222222222222");
    centerPanel.add(text2, constraint); 
    JScrollPane scroll = new JScrollPane(centerPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    frame.add(scroll, BorderLayout.CENTER);
    frame.setVisible(true);
}

/**
 * Create a Gridbag Constraint
 * @param text
 * @return
 */
private void changeConstraint(int gridx, int gridy){
    constraint.anchor = GridBagConstraints.FIRST_LINE_START;
    constraint.fill = GridBagConstraints.HORIZONTAL;
    constraint.weighty = 0;
    constraint.weightx = 1.0;
    constraint.gridx = gridx;
    constraint.gridy = gridy;
}

/**
 * Create a Textarea
 * @param text
 * @return
 */
private JTextArea createTextArea(String text){
    JTextArea textarea = new JTextArea(text);
    textarea.setWrapStyleWord(true);
    textarea.setLineWrap(true);
    return textarea;

}

}

1 个答案:

答案 0 :(得分:3)

一种可能性:考虑创建一个使用GridBagLayout的JPanel,并将JTextAreas添加到此JPanel,确保将weightx设置为0并将weighty设置为非零值,例如1.0。然后将JPanel放入JScrollPane,将JScrollPane放入GUI。