GridBagLayout & JScrollPane: how to reduce row height?
Asked Answered
T

2

1

See below a simple test code using a GridBagLayout (2 rows, 2 component on row 0, 1 component on row 1). Although I have specified weighty to be 0.01 for first row and 1 for second row, the ratio on the screen looks more like 0.3 vs. 0.7. It seems that the height of the first row is resized so that the whole textarea fits in it.

How can I reduce the height of the first row, so that the scroll bars of the JScrollPane will appear?

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);

    }
}
Titre answered 26/4, 2012 at 12:37 Comment(0)
U
3

Set the number of rows on the JTextArea so that the preferredSize of the textarea and scrollpane will adjust to that number of rows. In case there is an excessive number of rows in the text of the textarea, the scrollbar will appear.

Underdrawers answered 26/4, 2012 at 12:47 Comment(0)
F
3

weight - Specifies how to distribute extra vertical space. So if available space is bigger than sum of preferred sizes then extra pixes are distributed according to the weight values.

Fougere answered 26/4, 2012 at 12:46 Comment(0)
U
3

Set the number of rows on the JTextArea so that the preferredSize of the textarea and scrollpane will adjust to that number of rows. In case there is an excessive number of rows in the text of the textarea, the scrollbar will appear.

Underdrawers answered 26/4, 2012 at 12:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.