GridBagLayout没有显示JTextArea,并在中心显示面板

时间:2012-03-21 18:59:06

标签: java swing layout gridbaglayout

在下面的代码中,当我将JTextArea添加到主面板时,它不会显示。当我添加controlPanel时,它会显示在中心,而不是边缘。我是GridBagLayout的新手,所以我假设我错过了一些简单的东西。

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextArea;

public class Main {

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

    public Main() {
        JFrame frame = new JFrame();

        JPanel mainPanel = new JPanel();
        JPanel controlPanel = new JPanel();

        mainPanel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        controlPanel.add(new JButton("Play"));
        controlPanel.add(new JButton("Pause"));
        controlPanel.add(new JSpinner());
        JTextArea textArea = new JTextArea();

        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 3;
        c.gridwidth = 3;
        mainPanel.add(textArea, c);
        // mainPanel.add(controlPanel, c);
        frame.add(mainPanel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 700);
        frame.setLocation(250, 100);
        frame.setVisible(true);
    }
}

编辑:这是约束对您的建议的看法。 textArea仍未显示。

        c.gridx = 0;
        c.gridy = 0;
//      c.gridheight = 3;
//      c.gridwidth = 3;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(textArea, c);
        // mainPanel.add(controlPanel, c);
        frame.add(mainPanel);

2 个答案:

答案 0 :(得分:2)

不要忘记权重锚点:

    c.weightx = 1.0;
    c.weighty = 1.0;
    c.anchor = GridBagConstraints.NORTHWEST;

修改
将行和列值添加到JTextArea的示例:

    controlPanel.add(new JButton("Play"));
    controlPanel.add(new JButton("Pause"));
    controlPanel.add(new JSpinner());

    JTextArea textArea = new JTextArea(20, 40);

    c.gridx = 0;
    c.gridy = 0;
    c.gridheight = 3;
    c.gridwidth = 3;
    c.weightx = 1.0;
    c.weighty = 1.0;
    c.anchor = GridBagConstraints.NORTHWEST;
    mainPanel.add(new JScrollPane(textArea), c);

答案 1 :(得分:1)

我完全认真的回答是不使用GridBagLayout。将GridBagLayout留给GUI表单构建器。

如果您想手动构建GUI(我建议手工构建它们并避免使用表单构建器,BTW)那么使用BoxLayouts的嵌套面板的BorderLayout通常是您最好的选择。