import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ProgressMonitor;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ProgressMonitorDemo extends JFrame {
public static void main(String arg[]) {
new ProgressMonitorDemo();
}
public ProgressMonitorDemo() {
int height;
int width;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); } } );
setLocation(200,150);
Container pane = getContentPane();
ProgressMonitor monitor = new ProgressMonitor(this,
"Monitoring thread execution",
"",
0,
100);
monitor.setProgress(0);
JLabel label = new JLabel("Window of main program");
pane.setLayout(null);
Insets insets = pane.getInsets();
Dimension dim = label.getPreferredSize();
int x = insets.left + 20;
int y = insets.top + 20;
label.setBounds(x,y,dim.width,dim.height);
pane.add(label);
width = x + dim.width + 20 + insets.left;
height = y + dim.height + 40 + insets.bottom;
ProgressMonitorDemoTask task = new ProgressMonitorDemoTask(monitor);
task.start();
setSize(width,height);
setVisible(true);
}
}
class ProgressMonitorDemoTask implements Runnable {
private boolean running;
private Thread looper;
private ProgressMonitor monitor;
private int value;
ProgressMonitorDemoTask(ProgressMonitor monitor) {
this.monitor = monitor;
running = false;
}
public void start() {
if(!running) {
value = 0;
monitor.setProgress(value);
running = true;
looper = new Thread(this);
looper.start();
}
}
public void run() {
try {
while(running) {
Thread.sleep(200);
if(monitor.isCanceled())// 如果用户单击进度对话框中的 Cancel 按钮,则返回 true。
running = false;
monitor.setProgress(++value);
monitor.setNote(value + "% complete");
if(value >= 100)
running = false;
}
} catch(Exception e) {
System.out.println(e.getStackTrace());
}
}
}
Java6学习笔记18——利用Swing创建监视任务的进度条
最新推荐文章于 2021-02-26 07:59:51 发布