GridBagLayout& JScrollPane:如何减少行高? [英] GridBagLayout & JScrollPane: how to reduce row height?

查看:117
本文介绍了GridBagLayout& JScrollPane:如何减少行高?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用GridBagLayout(行0上的2行,2个组件,第1行上的1个组件)查看下面的简单测试代码。虽然我已经指定 weighty 为第一行为0.01,第二行为1,但屏幕上的比率看起来更像是0.3对0.7。似乎第一行的高度调整大小,以便整个textarea适合它。

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.

如何减小第一行的高度,以便滚动JScrollPane的栏会出现吗?

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

    }
}


推荐答案

设置JTextArea上的行数,以便textarea和scrollpane的preferredSize将调整为该行数。如果textarea文本中的行数过多,则会显示滚动条。

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.

这篇关于GridBagLayout& JScrollPane:如何减少行高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆