在Java中更新JTextArea

use*_*210 0 java swing repaint jtextarea

在我的程序中,我加载a JTextArea以在单击按钮时显示一些文本.我添加了ActionListener并编写了一个loadQuestion()方法,但由于某种原因组件没有更新.该组件包含在另一个我通过get()set()方法访问的文件中.我在loadQuestion()方法中运行了repaint()revalidate()方法,并在方法中再次运行setTextArea(),但它似乎仍然无法工作!任何指针将不胜感激 - 提前感谢

public void loadQuestion () {
    JTextArea tempArea = quizDisplay.getTextArea();
    String text = "Hello World!!";
    tempArea.append("Hi");
    quizDisplay.setTextArea(tempArea);
    quizDisplay.revalidate();
    quizDisplay.repaint();

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*bin 6

通常,当您将某些文本附加到可见文本时JTextArea,无需打电话revalidate或您repaint自己.该JTextArea知道它已经改变,并会采取其重绘的照顾.也无需再次设置文本区域.

此外,所有与Swing相关的操作都应该在EDT(事件调度线程)上进行.

所以你的代码最终看起来像

public void loadQuestion () {
    JTextArea tempArea = quizDisplay.getTextArea();
    tempArea.append("Hi");
}
Run Code Online (Sandbox Code Playgroud)

并且loadQuestion应该在EDT上调用该方法,这通常是从ActionListener按下按钮时调用它的情况.

查看Swing教程,了解使用JTextArea的示例,它们或多或少相同(来自我链接的源代码的引用)

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();

    //Make sure the new text is visible, even if there
    //was a selection in the text area.
    textArea.setCaretPosition(textArea.getDocument().getLength());
}
Run Code Online (Sandbox Code Playgroud)