有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法将字符串附加到jtextarea

public class Main {

    private static void createAndShowGUI()  {

        JFrame frame1 = new JFrame("FINAL YEAR PROJECT VER 1.0");

        frame1.setSize(500,500);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        FlowLayout experimentLayout = new FlowLayout();
        experimentLayout.setAlignment(FlowLayout.CENTER);
        frame1.setLayout(experimentLayout);

        JTextArea jtextarea = new JTextArea(200,200);
        JScrollPane scrollingArea = new JScrollPane(jtextarea);

        frame1.getContentPane().add(jtextarea);
        frame1.getContentPane().add(scrollingArea, FlowLayout.CENTER);

         jtextarea.setText("Welcome to Document-Query Similarity System Based On Weblogs");



        frame1.setVisible(true);
    }


    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

我试图在JTextarea上使用setText()方法显示文本。但是,该字符串不会显示。我错过了什么


共 (2) 个答案

  1. # 1 楼答案

    替换:

    JTextArea jtextarea = new JTextArea();
    

    而不是:

    JTextArea jtextarea = new JTextArea(200, 200);
    

    构造器的文档中说参数不是以像素为单位的:

    Constructs a new empty TextArea with the specified number of rows and columns. A default model is created, and the initial string is null.

  2. # 2 楼答案

    它就在那里,只要把文本区域缩小就行了。比如:

    JTextArea jtextarea = new JTextArea(20,20);
    

    如果它是当前大小,你就看不到文本。无法滚动到文本的部分原因是添加文本区域和滚动条的方式不正确。更好的方法是:

        frame1.setLayout(new BorderLayout());
        ...
        //delete the addition of the textarea to the frame, you already put it in the scroll pane.
        frame1.getContentPane().add(scrollingArea, BorderLayout.CENTER);