首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

进度条有关问题ProgressMonitor

2012-06-20 
进度条问题ProgressMonitorJava codeimport java.awt.Buttonimport javax.swing.JFrameimport javax.swi

进度条问题ProgressMonitor

Java code
import java.awt.Button;import javax.swing.JFrame;import javax.swing.ProgressMonitor;public class Progress extends JFrame {         private ProgressMonitor pm = new ProgressMonitor(this,"Monitoring Progress","Test",0,100);         Button but = new Button("点击");    public Progress(){        pm.setProgress(0);        pm.setMillisToPopup(1000);        this.add(but);        but.addActionListener(new ActionListener(){                           public void actionPerformed(ActionEvent arg0) {                for(int i = 0;i<101;i++){//设置断点,一步一步循环                    pm.setProgress(i);                }                            }            });        this.setSize(300,200);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setVisible(true);    }    public static void main(String[] args) {        new Progress();    }    }

设置断点后点击按钮,运行到pm.setProgress(i)时,有个框出来,但不是正常的,里面什么都没,而且还卡住了
为什么?请各位指教,谢谢咯

[解决办法]
google了个例子。。


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ProgressMonitorDemo extends JPanel
implements ActionListener {
public final static int ONE_SECOND = 1000;

private ProgressMonitor progressMonitor;
private Timer timer;
private JButton startButton;
private LongTask task;
private JTextArea taskOutput;
private String newline = "\n";

public ProgressMonitorDemo() {
super(new BorderLayout());
task = new LongTask();

//Create the demo's UI.
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);

taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5,5,5,5));
taskOutput.setEditable(false);

add(startButton, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

//Create a timer.
timer = new Timer(ONE_SECOND, new TimerListener());
}

class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
progressMonitor.setProgress(task.getCurrent());
String s = task.getMessage();
if (s != null) {
progressMonitor.setNote(s);
taskOutput.append(s + newline);
taskOutput.setCaretPosition(
taskOutput.getDocument().getLength());
}
if (progressMonitor.isCanceled() || task.isDone()) {
progressMonitor.close();
task.stop();
Toolkit.getDefaultToolkit().beep();
timer.stop();
if (task.isDone()) {
taskOutput.append("Task completed." + newline);
} else {
taskOutput.append("Task canceled." + newline);

}
startButton.setEnabled(true);
}
}
}

public void actionPerformed(ActionEvent evt) {
progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,
"Running a Long Task",
"", 0, task.getLengthOfTask());
progressMonitor.setProgress(0);
progressMonitor.setMillisToDecideToPopup(2 * ONE_SECOND);

startButton.setEnabled(false);


task.go();
timer.start();
}
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.
JFrame frame = new JFrame("ProgressMonitorDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
JComponent newContentPane = new ProgressMonitorDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

abstract class SwingWorker {
private Object value; // see getValue(), setValue()
private static class ThreadVar {
private Thread thread;
ThreadVar(Thread t) { thread = t; }
synchronized Thread get() { return thread; }
synchronized void clear() { thread = null; }
}

private ThreadVar threadVar;

/** 
* Get the value produced by the worker thread, or null if it 
* hasn't been constructed yet.
*/
protected synchronized Object getValue() { 
return value; 
}

/** 
* Set the value produced by worker thread 
*/
private synchronized void setValue(Object x) { 
value = x; 
}

public abstract Object construct();

/**
* Called on the event dispatching thread (not on the worker thread)
* after the <code>construct</code> method has returned.
*/
public void finished() {
}
public void interrupt() {
Thread t = threadVar.get();
if (t != null) {
t.interrupt();
}
threadVar.clear();
}
public Object get() {
while (true) {
Thread t = threadVar.get();
if (t == null) {
return getValue();
}
try {
t.join();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}


/**
* Start a thread that will call the <code>construct</code> method
* and then exit.
*/
public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() { finished(); }
};

Runnable doConstruct = new Runnable() { 
public void run() {
try {
setValue(construct());
}
finally {
threadVar.clear();
}

SwingUtilities.invokeLater(doFinished);
}
};

Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}

/**
* Start the worker thread.
*/
public void start() {
Thread t = threadVar.get();
if (t != null) {
t.start();
}
}
}
class LongTask {
private int lengthOfTask;
private int current = 0;
private boolean done = false;
private boolean canceled = false;


private String statMessage;

public LongTask() {
//Compute length of task...
//In a real program, this would figure out
//the number of bytes to read or whatever.
lengthOfTask = 1000;
}

/**
* Called from ProgressBarDemo to start the task.
*/
public void go() {
final SwingWorker worker = new SwingWorker() {
public Object construct() {
current = 0;
done = false;
canceled = false;
statMessage = null;
return new ActualTask();
}
};
worker.start();
}

/**
* Called from ProgressBarDemo to find out how much work needs
* to be done.
*/
public int getLengthOfTask() {
return lengthOfTask;
}

/**
* Called from ProgressBarDemo to find out how much has been done.
*/
public int getCurrent() {
return current;
}

public void stop() {
canceled = true;
statMessage = null;
}

/**
* Called from ProgressBarDemo to find out if the task has completed.
*/
public boolean isDone() {
return done;
}

/**
* Returns the most recent status message, or null
* if there is no current status message.
*/
public String getMessage() {
return statMessage;
}

/**
* The actual long running task. This runs in a SwingWorker thread.
*/
class ActualTask {
ActualTask() {
//Fake a long task,
//making a random amount of progress every second.
while (!canceled && !done) {
try {
Thread.sleep(1000); //sleep for a second
current += Math.random() * 100; //make some progress
if (current >= lengthOfTask) {
done = true;
current = lengthOfTask;
}
statMessage = "Completed " + current +
" out of " + lengthOfTask + ".";
} catch (InterruptedException e) {
System.out.println("ActualTask interrupted");
}
}
}
}
}
[解决办法]
这个简单,用邮箱发给你吧!

热点排行