java - GridBagLayout 中组件的大小不正确

标签 java swing resize gridbaglayout preferredsize

我正在用 Java 制作一个简单的界面。我想在顶部有一个设置大小为 200*20 的 JButton,在其正下方有一个封装 JTextArea 的 JScrollPane。该字段的大小应该是它所在的 JPanel 的剩余宽度和高度(但最小为 640*480),并且在放大/缩小窗口时必须调整大小(直到其最小尺寸)。

我尝试使用 GridBagLayout 进行此操作,但这似乎不起作用。有人知道我该如何解决这个问题吗?

    //Initialize components
    Dimension minSize = new Dimension(640, 480);
    info = new JTextArea("hello");
    info.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(info);
    scrollPane.setMinimumSize(minSize);
    JButton update = new JButton("update");
    JPanel jp = new JPanel();
    jp.setLayout(new GridBagLayout());
    GridBagConstraints grid = new GridBagConstraints();

    //add components
    grid.fill = GridBagConstraints.NONE;
    grid.anchor = GridBagConstraints.NORTHWEST;
    grid.gridheight = 1;
    grid.gridwidth = 1;
    grid.weighty = 1.0;
    grid.weightx = 1.0;
    grid.gridx = 0;
    grid.gridy = 0;

    jp.add(update, grid);

    grid.fill = GridBagConstraints.BOTH;
    grid.gridx = 0;
    grid.gridy = 1;
    grid.weighty = 15;
    grid.gridheight = 15;
    grid.gridwidth = 15;

    jp.add(scrollPane, grid);

    this.add(jp,BorderLayout.NORTH);

这就是现在的样子:enter image description here正如我之前所描述的,这不是我想要的; TextArea 需要填满整个屏幕(因此它需要更高)。

我该怎么做?

最佳答案

this.add( jp, BorderLayout.CENTER );

按照规定in the documentation :

The components are laid out according to their preferred sizes and the constraints of the container's size. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over.

关于java - GridBagLayout 中组件的大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15867742/

相关文章:

java - 无法编写JSON:无限递归(StackOverflowError)

java - 当通过公共(public) API 测试很难看时,如何在 Java 中测试私有(private)方法?

java - 从jtable导出到excel时如何合并列?使用 Apache POI

MATLAB:自动调整 GUI 组件/字体的大小

Matlab 轴在非交互模式下调整大小行为异常

java - 如何读取由空格分隔的 int 和字符串混合的文本文件并将每个文件存储到数组中

java - <c :forEach not rendering with tomcat 7

java - 如何获取 JTextPane 行数

java - 单击 TableRowSorter 时获取所选行中的用户对象

jquery - 如果调整高度,模式弹出窗口将适合浏览器 View