gpt4 book ai didi

java - JProgressBar 不更新,找不到线索

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

干得好,现在我只想知道为什么如果我在 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(); } }

need some help around , i can't get the JProgressBar to update, i can't use SwingWorker, i have to solve this without it . the variable Path.operationProgress is a static variable from a "Path" class instance, and it's updated from another thread, so i think the PBar and Path instances are both executed in user's Threads and not in the EDT . here is the Code of the progress bar :

    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();
}}}
}

this is the action that launches the threads :

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)

{
Thread sa = new Thread(){ @Override public void run(){ result = p.SimulatedAnnealing(neighborHood_Type); String lastCostString = result.Cost() + ""; lastCostLabel.setText(lastCostString); }}; sa.start(); Pbar pb = new Pbar(operationProgressBar); pb.start(); } //Some other Stuff ... }

最佳答案

如果您不能使用 SwingWorker 则使用 SwingUtilities.invokeLater,例如:

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 组件进行操作,这是没有办法解决的。

关于java - JProgressBar 不更新,找不到线索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349523/

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