JScrollPane不在JTextArea上显示

时间:2015-03-05 18:45:57

标签: java swing jscrollpane 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);

1 个答案:

答案 0 :(得分:1)

您的代码对我来说很合适。我猜你正在将textarea添加到组件层次结构而不是滚动窗格。请务必致电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