干得好,现在我只想知道为什么如果我在 while 循环中添加下面的 System.out.println 指令,进度会显示在 Gui 中的 cmd 和 Pgbar 上? :
while(progress < 99){
System.out.println("into while of PBar Thread progress = "+progress);
if(progress != Path.operationProgress){
operationProgressBar.setValue(progress);
progress = Path.operationProgress;
operationProgressBar.repaint(); } }
需要一些帮助,我无法更新 JProgressBar,我
无法使用 SwingWorker,我必须在没有它的情况下解决这个问题。变量
Path.operationProgress 是“Path”类中的静态变量
实例,并且它是从另一个线程更新的,所以我认为 PBar
和 Path 实例都在用户的线程中执行,而不是在
美东时间 。这是进度条的代码:
import javax.swing.*;
public class Pbar extends Thread {
JProgressBar operationProgressBar;
public Pbar(JProgressBar operationProgressBar) {
this.operationProgressBar = operationProgressBar;
}
@Override
public void run() {
int progress = Path.operationProgress;
while(progress < 99) {
if(progress != Path.operationProgress) {
operationProgressBar.setValue(progress);
progress = Path.operationProgress;
operationProgressBar.repaint();
}}}
}
这是启动线程的操作:
private javax.swing.JProgressBar operationProgressBar;
private javax.swing.JLabel pathImage;
private javax.swing.JButton simulatedAnnelingButton;
public class TSPGUI extends javax.swing.JFrame {
TSPMG tspInstance;
Path p, result;
String filename = "";
int neighborHood_Type = 1, i = 0;
// ......Constructor Stuff and init()
private void simulatedAnnelingButtonActionPerformed(java.awt.event.ActionEvent evt)
{
线程 sa = 新线程(){
@覆盖
公共无效运行(){
结果 = p.SimulatedAnnealing(neighborHood_Type);
String lastCostString = result.Cost() + "";
lastCostLabel.setText(lastCostString);
}};
sa.start();
Pbar pb = new Pbar(操作进度条);
pb.start();
}
//其他一些东西...
}
如果你不能使用SwingWorker
然后使用SwingUtilities.invokeLater
, e.g.:
if (progress != Path.operationProgress) {
final int progressCopy = progress; // Probably not final so copy is needed
SwingUtilities.invokeLater(new Runnable() {
@Override
void run() {
operationsProgressBar.setValue(progressCopy);
}
});
}
注意:执行此操作时,使用的所有内容run
必须是最终的,或者必须有其他措施来访问变量。这段代码在这方面具有象征意义。
您需要在事件调度线程之外对 Swing 组件进行操作,没有办法解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)