无法从另一个函数向 Java 中的 JTextArea 添加文本



我用Java做了一个简单的程序,它只包含一个文本区域和一个按钮。该按钮假设添加一个"文本"。但是,它对我不起作用。

附带说明:我试图使我的函数尽可能短。(我不想要代码行太多的函数)

首先,我创建 JFrame

private static void createFrame()
{
    //Build JFrame
    JFrame frame = new JFrame("Text Frame");
    frame.setLayout(null);
    frame.setSize(500,400);
    Container contentPane = frame.getContentPane();
    contentPane.add(textScrollPane());
    contentPane.add(buttonAddText());
    //Set Frame Visible
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

然后是文本区域和滚动窗格(用于添加滚动条)

private static JTextArea textArea()
{
    JTextArea output = new JTextArea();
    output.setLineWrap(true); // Text return to line, so no horizontal scrollbar
    output.setForeground(Color.BLACK);
    output.setBackground(Color.WHITE);
    return output;
}
private static JScrollPane textScrollPane()
{
    JScrollPane scrollPane2 = new JScrollPane(textArea());
    scrollPane2.setBounds(0, 0, 490, 250);
    return scrollPane2;
}

最后,按钮

private static JButton buttonAddText()
{
    JButton testbutton = new JButton("TEST");
    testbutton.setBounds(20, 280, 138, 36);
    testbutton.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e)
        {
            //action listener here
            textArea().insert("TEXT",0);
            System.out.println("Button Tested!");
        }
    });
    return testbutton;
}

当我单击按钮时,它不会执行任何操作。我只想在 JTextArea 中添加一个文本。我忘记了什么吗?

textArea() 每次被调用时都会返回一个新的 JTextArea。因此,您的 buttonAddText() 函数正在调用 textArea() 并将文本添加到新创建的文本区域,该文本区域不包含在滚动窗格中。

您需要将文本区域的引用传递给 textScrollPane() 和 buttonAddText() 函数。

这样的东西会起作用:

JTextArea jta = textArea();
contentPane.add(textScrollPane(jta));
contentPane.add(buttonAddText(jta));

更改 textScrollPane() 和 buttonAddText(),以便它们接受 JTextArea 参数,并且不再在这些函数中调用 textArea() 来创建新的文本区域。而是使用传递给函数的 JTextArea 对象。

最新更新