不错的工作,现在我只想知道为什么如果我加入while循环指令System.out.println下面的进度显示在这两个cmd和Pgbar在桂? :JProgressBar不更新,找不到线索
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实例都在用户线程中执行,而不是在EDT中执行 EDT。这里是进度条的代码:
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 =新的Thread(){ @覆盖 公共无效的run (){ result = p.SimulatedAnnealing(neighborHood_Type); String lastCostString = result.Cost()+“”; lastCostLabel.setText(lastCostString); }}; sa.start(); Pbar pb = new Pbar(operationProgressBar); pb.start(); } // 一些其他的东西...... }
尽管你的关怀尝试做的事情在后台线程,你的问题闻起来像一个线程问题 - 要么或不确定JProgressBar更新是不显示的一个。没有更多的代码,但很难说。如果上面的代码在后台线程上运行,则必须小心地调用EDT上的进度条setValue(...),虽然这不能解决问题,但可能会防止出现间歇性异常。我建议你向我们展示更多代码,最好是[sscce](http://sscce.org)。 – 2012-02-19 13:28:13
请对代码块使用一致的逻辑缩进,并且在每一个代码行之后不需要空行! – 2012-02-19 13:38:44
另外,你应该努力实现Runnable而不是扩展Thread。另外你如何运行线程?你是在调用'start()'还是'run()'? ......你的问题会导致更多的问题再次被[sscce](http://sscce.org)回答。我知道我在这里听起来像是一个破碎的记录,但是如果写得好的话,那些东西是很有帮助的。 – 2012-02-19 13:43:33