JScrollPane 不显示在 JTextArea 上

JScrollPane not displaying on JTextArea

我正在尝试实施的 JScrollPane 不起作用。我想将它添加到我的 JTextArea,但由于某些原因它不想显示

//JTEXTBOX
textArea = new JTextArea();
textArea.setEditable(false);

//JSCROLLPANE
JScrollPane scroll1 = new JScrollPane(textArea);
scroll1.setPreferredSize(new Dimension(200, 250));
scroll1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

你的代码对我来说工作得很好。我猜您是将文本区域而不是滚动窗格添加到组件层次结构中。确保您调用 parent.add(scrollpane) 而不是 parent.add(textarea).

看这个例子:

import java.awt.Dimension;
import java.awt.EventQueue;

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

public class TestTextArea {
    private JTextArea textArea;

    public TestTextArea() {
    }

    private void initUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // JTEXTBOX
        textArea = new JTextArea(10, 25);
        textArea.setEditable(false);
        textArea.setText("Here is my textarea\nI can finally see it.\nYeah!!! :-)");

        // JSCROLLPANE
        JScrollPane scroll1 = new JScrollPane(textArea);
        scroll1.setPreferredSize(new Dimension(200, 250));
        scroll1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        frame.add(scroll1);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    TestTextArea test = new TestTextArea();
                    test.initUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

注意:忘记使用 setPreferredSize 并尝试通过在其构造函数中提供行和列来提示 JTextArea 您喜欢的大小。