经过多次尝试使JProgressBar
按预期工作的尝试后,我终于成功实现了自己的目标。我曾使用@MadProgrammer的advice,并使用SwingWorker
最终得到我想要的程序工作。将默认光标更改为忙光标不能正常工作
现在,当我的JProgressBar
从0%变为100%时,我希望光标变为BUSY_CURSOR http://telcontar.net/Misc/screeniecursors/Cursor%20hourglass%20white.png。我GOOGLE了,发现,
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
方法:
public void actionPerformed(ActionEvent e)
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Task task=new Task();
task.addPropertyChangeListener(this);
task.execute();
dialog.setVisible(true);
}
的propertyChange
方法:
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());
}
}
当我按button
时,带有JProgressBar的JDialog出现,JProgressBar从0%变为100%。在此期间,光标需要更改为BUSY_CURSOR http://telcontar.net/Misc/screeniecursors/Cursor%20hourglass%20white.png(忙光标),当JProgressBar达到100%时,需要恢复正常光标(NORMAL_CURSOR http://fc05.deviantart.net/fs70/i/2011/008/1/4/mouse_cursor_windows_by_mikima-d36oslj.png)。
问题是,当我按button
时,光标变为繁忙的光标一瞬间,然后变回原来的光标。我希望光标很忙,直到JProgressBar达到100%。
我已经添加代码以将光标转换为忙碌光标在actionPerformed
方法和恢复正常的光标在嵌套类Task
的done
方法。请注意,我还包括必要的软件包。
- 是什么导致了这个问题?
- 我该如何解决?
我应该使用
setCursor(null);
或
setCursor(Cursor.getDefaultCursor());
恢复光标?
现在我明白了。这正是我正在寻找的。我认为'setCursor'在整个程序中设置了给定的光标。为什么我的代码工作?因为GUI类,“扩展JFrame”。那么,这一次我将光标设置为JFrame? Arrgh!谢谢! –