我正在编写一个应用程序,它可以进行一些音频分析(用作吉他调音器,并添加和弦估计和其他一些东西),但我在使用 GUI 时遇到了一些问题。第一个问题是我有一个按钮,单击该按钮后应更改其显示的文本。单击时,文本不会更改,但肯定会到达应该更改它的代码行。
另一件事是我需要一个 SwingWorker 来重复执行(完成后重新启动)并每次更新 GUI。正如我目前的代码所示,我有一个 while 循环重复执行我的 SwingWorker,但这导致 GUI 变得无响应,因为它在 EDT 中运行(大概)。让 SwingWorker 重复执行的最佳方法是什么?我应该创建一个新线程来运行循环,还是其他什么?
我的内部 ActionListener 类的代码如下:
private class TunerListener implements ActionListener {
private boolean firstUpdate = true;
private volatile boolean executing = false;
private final SwingWorker<Void, Void> tunerWorker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() {
model.update();
return null;
}
@Override
protected void done() {
if (!this.isCancelled()) {
prev.setText(model.getPrev());
currentNote.setText(model.getNote());
next.setText(model.getNext());
frequency.setText(model.getFrequency());
switch (model.getOffset()) {
case -2:
light_2.setIcon(onRed);
light_1.setIcon(off);
light0.setIcon(offBig);
light1.setIcon(off);
light2.setIcon(off);
break;
case -1:
light_2.setIcon(off);
light_1.setIcon(onRed);
light0.setIcon(offBig);
light1.setIcon(off);
light2.setIcon(off);
break;
case 0:
light_2.setIcon(off);
light_1.setIcon(off);
light0.setIcon(onGreen);
light1.setIcon(off);
light2.setIcon(off);
break;
case 1:
light_2.setIcon(off);
light_1.setIcon(off);
light0.setIcon(offBig);
light1.setIcon(onRed);
light2.setIcon(off);
break;
case 2:
light_2.setIcon(off);
light_1.setIcon(off);
light0.setIcon(offBig);
light1.setIcon(off);
light2.setIcon(onRed);
break;
}
}
}
};
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("tune")) {
if (!executing) {
tune.setText("Stop Tuning");
executing = true;
while (executing) {
tunerWorker.execute();
firstUpdate = false;
}
firstUpdate = true;
} else {
tune.setText("Start Tuning");
executing = false;
tunerWorker.cancel(true);
firstUpdate = true;
}
}
}
}
编辑:按钮文本问题似乎现已修复,但我仍然无法让此 SwingWorker 正常工作。我尝试完全删除 while 循环并让它从其 did() 方法中重新执行自身,但这似乎并没有真正帮助问题......
最佳答案
“SwingWorker
只设计为执行一次。”相反,控制工作线程的执行和生命周期,如example所示。 .
关于java - SwingWorker的重复执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460495/