所以我正在制作的程序使用了 2 个线程:一个用于 GUI,一个用于完成工作。
我希望来自工作线程/类的更新在 GUI 类的 JTextArea 上打印出来。 我尝试的一切似乎都不起作用。我在将文本添加到 JTextArea 的行之后添加了一些行以在控制台上打印出文本,以确保它已到达该行,但每次控制台都收到文本但 GUI 中的 JTextArea 没有发生任何变化。
public static void consoleText(String consoleUpdate){
GUI.console.append(consoleUpdate);
}
我在工作课上尝试过这个,但没有任何反应。 有人知道如何解决我的问题吗?
编辑:
MAIN.JAVA
public class main {
public static void main(String[] args) {
Thread t1 = new Thread(new GUI());
t1.start();
}
GUI.JAVA
public class GUI extends JFrame implements Runnable{
public static JTextArea console;
private final static String newline = "\n";
public void run(){
GUI go = new GUI();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(350, 340);
go.setVisible(true);
}
public GUI(){
setLayout(new FlowLayout());
console = new JTextArea(ConsoleContents, 15, 30);
add(console);
}
WORK.JAVA
...{
consoleText("\nI want this text on the JText Area");
}
public static void consoleText(String consoleUpdate){
GUI.console.append(consoleUpdate);
}
最佳答案
首先,如前所述,您的 GUI 应该仅在事件调度线程上运行。
正如所写,您的 GUI 类做两件事:它是一个框架,一个可运行的,两者都是 完全独立使用。事实上,在您的 GUI 对象上调用“运行”会创建另一个不相关的 GUI 对象。这可能就是您什么也没看到的原因。
所以我建议您将以下内容作为主要内容:
... main(...) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI gui= new GUI();
gui.setVisible(true); // and other stuff
}
});
}
(顺便说一句,我还建议摆脱所有“静态”字段。这可能是来源 你的问题,以及“运行”方法的奇怪地方)。
现在,我假设您从另一个线程调用的“consoleText”方法不应该 直接修改文本,但调用 SwingUtilities.invokeLater() 来这样做:
public void consoleText(final String consoleUpdate){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.append(consoleUpdate);
}
});
(“最终”声明很重要,因为它允许 Runnable 使用 consoleUpdate 变量)。
关于java - 将文本添加到 JTextArea 时出现问题( append 或设置文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053107/