gpt4 book ai didi

java - JTextArea 中正在执行写入操作

转载 作者:行者123 更新时间:2023-11-30 03:51:08 24 4
gpt4 key购买 nike

我编写了一个应用程序,它根据 x : f(x) 列表创建图形图像。在 GUI 中,它应该显示当前正在图形上写入的对,但 JTextArea 仅在生成图像的循环完成后显示消息。如何实时显示消息?

我想过使用多线程,但还是不行。

下面是图形生成器的代码:

public static void processFile(String filename, String currentDir){
File file = new File(filename);

LogWindow logWindow = showLogWindow();

String line, function;
TreeMap<Integer, Integer> dataSet = null;

try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
logWindow.log("Starting processing of file " + file.getName());
skipHeader(reader, Constantes.HEADER_LINES);
while ((line = reader.readLine()) != null){
if(line.startsWith("function ")){
function = line.substring(25, 35).trim();

if(dataSet != null){
logWindow.log("Graph of function " + function + " created.");
Graph demo = new Graph(dataSet);
demo.writeAsPNG(currentDir + File.separator + function + ".png");
}

dataSet = new TreeMap<Integer, Integer>();
}else{
int x = Integer.valueOf(line.substring(20,25).trim());
int fX = Integer.valueOf(line.substring(25,30).trim());
dataSet.put(x, fx);
logWindow.log("Adding values of x = " + x + " and f(x) = " + fX);
}
}

//Writing last set of data
logWindow.log("Graph of function " + function + " created.");
Graph demo = new Graph(dataSet);
demo.writeAsPNG(currentDir + File.separator + function + ".png");
} catch (FileNotFoundException e) {
//TODO log this better
e.printStackTrace();
} catch (IOException e) {
//TODO log this better
e.printStackTrace();
}
}

这是 LogWindow 类的代码

public class LogWindow extends JPanel {
private JTextArea log;

public LogWindow() {
super(new BorderLayout());
log = new JTextArea(5,40);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
add(logScrollPane, BorderLayout.CENTER);
}

public void log(String message){
LogThread t = new LogThread(log, message);
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Log this better
e.printStackTrace();
}
}
}

class LogThread extends Thread{
JTextArea log;
String message;

public LogThread(JTextArea log, String message) {
this.log = log;
this.message = message;
}

@Override
public void run() {
log.append(message + Constantes.lineBreak);
log.setCaretPosition(log.getDocument().getLength());
}
}

提前致谢

最佳答案

  • 您的代码不完整,请发布 SSCCE/MVCE


  • 您对Concurency in Swing有疑问,Swing 是单线程的,所有更新都已可见 AWT/Swing GUI must be on EDT

  • 通过将 log.append(message + Constantes.lineBreak); 包装到 invokeLater()

  • 中快速修复
  • 不知道为什么会出现t.join();

<小时/>
  • (重复调用)代码行 log.setCaretPosition(log.getDocument().getLength()); 应替换为(仅适用于所有更新均在 EDT 上完成的情况)单个JTextArea/event 的定义。 JTextComponent

.

DefaultCaret caret = (DefaultCaret) log.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

关于java - JTextArea 中正在执行写入操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24432106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com