gpt4 book ai didi

java - 尝试在模态对话框中更新 JLabel

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:17 24 4
gpt4 key购买 nike

我有一个包含 JLabel 的模态对话框。此对话框调用另一个类中的方法,该方法执行长时间运行的查找 Activity 。我希望这个查找类更新从模态对话框传递的 JLabel。

我已经尝试从查找过程中的代码循环和定时器中更新 JLabel。 (我发现当模式对话框运行时,Swing 定时器的 actionPerformed 方法永远不会被调用。)自从实现定时器后,我将我的查找过程移到了一个单独的线程。

我的查找有效,但 JLabel 在过程结束之前仍然不会重新绘制。我将不胜感激。

这里是相关的方法。 DictionaryTuple 是一个包含两个字段的 POJO:一个列表和一个字符串。只是 getter 和 setter,但 dictionaryThread 确实可以访问 tupleList;请注意,在 dictionaryThread 完成之前,我们不会在这里触及它。

public List<DictionaryTuple> findTuples() {
tupleList = new ArrayList<DictionaryTuple>();
Thread dictionaryThread = new Thread(this); // This is the long-running lookup thread
dictionaryThread.start();

progressTimer = new Timer();
progressTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// progressCaption is updated in dictionaryThread
synchronized (progressCaption) {
lblProgress.setText(progressCaption);
}
lblProgress.repaint();
Thread.yield();
}
}, 250, 250);

try {
dictionaryThread.join();
} catch (InterruptedException e) {
} finally {
progressTimer.cancel();
lblProgress.setText("");
progressCaption = "";
}
return tupleList;
}

我也尝试过这种变体;在这种情况下,内部 run() 调用将一直保持到处理完成:

    progressTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
synchronized (progressCaption) {
System.out.println("Fire!");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Update");
lblProgress.setText(progressCaption);
lblProgress.repaint();
}});
}
}
}, 250, 250);

最佳答案

您需要准确地向我们展示您将对话框设置为可见的位置 -- 是在调用 findTuples() 之前还是之后方法?这很关键。

建议:

  • 始终在 Swing 事件线程或 EDT(事件调度线程)上更新 JLabel。
  • 不要使用 java.util.Timer 来更新 Swing 应用程序的组件。
  • 您可以使用 javax.swing.Timer 来更新 Swing 组件,但这在这里不起作用,除非您使用它来轮询后台进程。
  • 考虑将 SwingWorker 用于后台线程,然后通过 worker 的发布/处理方法或通过添加到 SwingWorker 的 PropertyChangeListener 更新 JLabel。
  • 将对话框设置为可见时调用您希望在对话框运行时运行的所有方法。

关于java - 尝试在模态对话框中更新 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318387/

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