切换水龙头后保持 textArea 大小

Keep textArea size after switching the tap

我有一个带有多个选项卡的简单 GUI: GUI

问题在于,将文本区域填充到底部后(filled console) and switching the tab - it completely breaks the markup (bottom-broken)

这里是textArea和Constraints的代码示例

JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        tabbedPanelOne.add(textArea);
        CustomAppender.setTextArea(textArea);

        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.gridy++;
        gbc.gridx = 0;
        gbc.gridwidth = 5;
        gbc.weightx = 1.0;
        gbc.weighty = 10.0;

        Font font = textArea.getFont();
        float size = font.getSize() - 4.0f;
        textArea.setFont(font.deriveFont(size));

        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        //textArea.setPreferredSize(new Dimension(500, 300));
        layout.setConstraints(textArea, gbc);

        /*
         * Scrolls for TextArea
         */
        JScrollPane scroll = new JScrollPane (textArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        tabbedPanelOne.add(scroll);
        layout.setConstraints(scroll, gbc);

//textArea.setPreferredSize(new Dimension(500, 300)); 工作正常,但它禁用了垂直滚动条。

layout.setConstraints(textArea, gbc);

首先,将组件添加到滚动窗格时,您绝不会尝试在组件上设置约束。 JScrollPane 使用它自己的自定义布局管理器,因此当您将组件添加到滚动窗格的视口时,您不需要做任何特殊的事情。

但是,最简单的解决方案是在添加到选项卡的面板上使用 BorderLayout。类似于:

JPanel top = new JPanel();
top.add(...);
JTextArea textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane( textArea );
JPanel main = new JPanel( new BorderLayout() );
main.add(top, BorderLayout.PAGE_START);
main.add(scrollPane, BorderLayout.CENTER);

现在滚动窗格将占用选项卡中所有可用的 space,并且在需要时会出现滚动条。