这样一段代码,希望能够在执行的时候,显示一个进度条。但是每次进度条都要等到执行完了才显示出来,为什么呢?
Progress p=new Progress(poi);
Thread th=new Thread(p);
try{
th.start();
//一段需要很长时间的代码
//th.interrupt();
}catch(Exception e){
//th.interrupt();
}
package com.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
public class Progress implements Runnable {
Timer tm;
ProgressMonitor pm;
JFrame poi;
int i;
public Progress(JFrame poi){
this.poi=poi;
}
public void run() {
ActionListener actionListener=new ActionListener(){
public void actionPerformed(ActionEvent e){
pm.setProgress(++i==100?1:i);
}
};
System.out.println(123);
tm=new Timer(200,actionListener);
pm=new ProgressMonitor(poi,"","正在导入,请稍候...",1,100);
pm.setMillisToDecideToPopup(0);
pm.setMillisToPopup(0);
tm.start();
}
}
Progress p=new Progress(poi);
Thread th=new Thread(p);
try{
th.start();
//一段需要很长时间的代码
//th.interrupt();
}catch(Exception e){
//th.interrupt();
}
package com.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
public class Progress implements Runnable {
Timer tm;
ProgressMonitor pm;
JFrame poi;
int i;
public Progress(JFrame poi){
this.poi=poi;
}
public void run() {
ActionListener actionListener=new ActionListener(){
public void actionPerformed(ActionEvent e){
pm.setProgress(++i==100?1:i);
}
};
System.out.println(123);
tm=new Timer(200,actionListener);
pm=new ProgressMonitor(poi,"","正在导入,请稍候...",1,100);
pm.setMillisToDecideToPopup(0);
pm.setMillisToPopup(0);
tm.start();
}
}
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.Timer;
public class Progress implements Runnable {
static boolean check=false;
Timer tm;
ProgressMonitor pm;
static JFrame poi;
int i;
public Progress(JFrame poi){
this.poi=poi;
}
public void run() {
ActionListener actionListener=new ActionListener(){
public void actionPerformed(ActionEvent e){
pm.setProgress(++i==100?101:i);
check=true;
dorun();
}
};
if(check){
}
tm=new Timer(50,actionListener);
pm=new ProgressMonitor(poi,"","正在导入,请稍候...",1,100);
pm.setMillisToDecideToPopup(0);
pm.setMillisToPopup(0);
tm.start();
}
public void dorun(){
if(i==101){
System.out.println("##############"+"123");
}
}
public static void main(String args[]){
Progress p=new Progress(poi);
Thread th=new Thread(p);
try{
th.start();
//一段需要很长时间的代码
//th.interrupt();
}catch(Exception e){
//th.interrupt();
}
}
}
我不太明白你的意思所以就照着我的意思改了一下
以前没用过线程,有些地方可能有问题,希望和你探讨.我现在想学这个.呵呵还望不吝赐教!!!