1

请参见下面使用 GridBagLayout 的简单测试代码(2 行,第 0 行有 2 个组件,第 1 行有 1 个组件)。虽然我已指定weighty第一行为 0.01,第二行为 1,但屏幕上的比率看起来更像 0.3 与 0.7。似乎第一行的高度已调整大小,以便整个文本区域适合其中。

如何降低第一行的高度,使 JScrollPane 的滚动条出现?

public class Test {

    public static void main(String... args) {
        String text = "text\n\n\n\n\n\n\n\ntext";
        JFrame frame = new JFrame();
        JTextArea area;
        JScrollPane pane;

        JPanel desktop = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 0.25;
        c.weighty = 0.05;
        area = new JTextArea(text);
        area.setBackground(Color.RED);
        pane = new JScrollPane(area);
        desktop.add(pane, c);

        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 0.75;
        c.weighty = 0.05;
        area = new JTextArea(text);
        area.setBackground(Color.BLUE);
        pane = new JScrollPane(area);
        desktop.add(pane, c);

        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = 1;
        c.weightx = 0;
        c.weighty = 1;
        c.gridwidth = 2;
        area = new JTextArea(text);
        area.setBackground(Color.GREEN);
        pane = new JScrollPane(area);
        desktop.add(pane, c);

        frame.setContentPane(desktop);
        frame.setPreferredSize(new Dimension(800, 600));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);

    }
}
4

2 回答 2

3

weight - 指定如何分配额外的垂直空间。因此,如果可用空间大于首选大小的总和,则根据权重值分配额外的像素。

于 2012-04-26T12:46:55.440 回答
3

设置 JTextArea 上的行数,以便 textarea 和滚动窗格的 preferredSize 将调整为该行数。如果 textarea 的文本行数过多,则会出现滚动条。

于 2012-04-26T12:47:48.590 回答