JTextArea 不能很好地与 JPanel 中的 JScrollPane 配合使用

JTextArea not working well with JScrollPane inside JPanel

我一直在尝试制作一个 JTextArea,我可以像在 Word 文档中那样编写它;当文本太宽时它环绕,当它太高时向下滚动)。
到目前为止,当它变得太宽时包裹效果很好。但是,滚动条不起作用。它确实出现了,但它永远不会再出现,这意味着无论如何都无法查看 JTextArea 原始尺寸之外的任何内容。
有谁知道我做错了什么?这是代码的样子;它是名为 panel 的 JPanel,稍后我通过将其添加到另一个 JPanel 来使用它,而 JPanel 又被添加到 JFrame。

JTextArea text = new JTextArea(rows, columns);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));
JScrollPane scroll = new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(scroll);

工作正常,当我删除 - text.setPreferredSize

import java.awt.Dimension;
import java.awt.HeadlessException;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class ScrollTest extends JFrame {

    public ScrollTest() throws HeadlessException {
        JTextArea text = new JTextArea(5, 20);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
//      text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));

        JScrollPane scroll = new JScrollPane(text);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(scroll);

        this.add(panel);

        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ScrollTest();
    }
}