经过多次尝试JProgressBar
按照预期的工作,我终于成功地实现了我的目标。我曾经用过@疯狂程序员's advice并使用了SwingWorker
最终让程序按我想要的方式工作。
Now, I want the cursor to change into
when my JProgressBar
goes from 0% to 100%. I've googled and found out that
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
是执行此操作的代码。我已经尝试过,但它没有按预期工作。
相关代码段:
JProgressBar progress;
JButton button;
JDialog dialog; //Fields of my GUI class
progress=new JProgressBar(JProgressBar.HORIZONTAL,0,100);
button=new JButton("Done");
dialog=new JDialog(); //Done from methods
progress.setValue(0);
progress.setStringPainted(true);
progress.setBorderPainted(true); //Also done from methods
button.addActionListener(this); //Also done from methods
dialog.setLayout(new FlowLayout(FlowLayout.CENTER));
dialog.setTitle("Please wait...");
dialog.setBounds(475,150,250,100);
dialog.setModal(true); //Also done from methods
dialog.add(new JLabel("Loading..."));
dialog.add(progress); //Also done from methods
这是actionPerformed
method:
public void actionPerformed(ActionEvent e)
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Task task=new Task();
task.addPropertyChangeListener(this);
task.execute();
dialog.setVisible(true);
}
The propertyChange
method:
public void propertyChange(PropertyChangeEvent evt) {
if("progress" == evt.getPropertyName()){
int progressnum = (Integer) evt.getNewValue();
progress.setValue(progressnum);
}
}
和嵌套类Task
:
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
int progressnum = 0;
setProgress(0);
while (progressnum < 100) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.err.println("An error occured:"+ex);
ex.printStackTrace();
}
progressnum ++;
setProgress(Math.min(progressnum, 100));
}
return null;
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
//setCursor(null); //turn off the wait cursor
setCursor(Cursor.getDefaultCursor()); //Is this one or the one above it right?
dialog.dispose();
progress.setValue(progress.getMinimum());
}
}
When I press button
, the JDialog with the JProgressBar appears and the JProgressBar goes from 0% to 100%. During this time, the cursor needs to be changed into
(busy cursor) and when the JProgressBar reaches 100%, the normal cursor(
) needs to be restored.
问题是,当我按button
,光标瞬间变为繁忙光标,然后又变回原始光标。我希望光标一直处于忙碌状态,直到 JProgressBar 达到 100%。
我添加了将光标转换为忙碌光标的代码actionPerformed
方法并恢复正常光标done
嵌套类的方法Task
。请注意,我还包含了必要的软件包。