进度条 Java [英] Progress Bar Java
问题描述
我正在使用 JProgressBar 来显示进度.但是,如何将进度条显示为从 0 到 100 的加载?我从互联网上获得了代码,除了没有加载进度条之外,它的工作正常.
I am using JProgressBar to show progress. But, How to show the progressBar as loading from 0 to 100? I got the code from internet and its working except the progressBar is not loading.
代码
progressFrame = new JFrame(); // frame to display progress bar
progressBar = new JProgressBar(0,100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressFrame.add(progressBar);
new SwingWorker<Void,Void>()
{
protected Void doInBackground() throws SQLException, ClassNotFoundException
{
Class.forName("oracle.jdbc.driver.OracleDriver");
progressBar.setValue(0);
frame.setEnabled(false); // frame = main frame
//tableclass creates a JTable with data from database
tableclass = new TheDatabaseTable(deptName);//it takes time to create
progressBar.setValue(50);
frame.getContentPane().removeAll();
frame.setContentPane(tableclass);
frame.validate();
frame.repaint();
progressBar.setValue(100);
//progressFrame.dispose();
return null;
};
protected void done()
{
//progressFrame.setVisible(false);
frame.setVisible(true);
progressFrame.dispose();
frame.setEnabled(true);
}
}.execute();
如果有人编辑上述代码以使其正常工作,我将不胜感激.谢谢.
I would appreciate if anyone edit the above code to work. Thank you.
推荐答案
为此您必须使用线程.设计一个实现 Runnable
接口的类,它将像这样更新值.
You have to use threads for that. Design a class that implements Runnable
interface which will update the values like this.
class ProgressBarUpdator implements java.lang.Runnable {
/**
* Progress bar that shows the current status
*/
private javax.swing.JProgressBar jpb = null;
/**
* Progress bar value
*/
private java.lang.Integer value = null;
/**
* Constructor
* @param jpb The progress bar this has to update
*/
public ProgressBarUpdator(javax.swing.JProgressBar jpb) {
this.jpb = jpb;
jpb.setMaximum(100);
}
/**
* Sets the value to the progress bar
* @param value Value to set
*/
public void setValue(java.lang.Integer value) {
this.value = value;
}
/**
* Action of the thread will be executed here. The value of the progress bar will be set here.
*/
public void run() {
do {
if (value != null) {
jpb.setValue((int)java.lang.Math.round(java.lang.Math.floor(value.intValue() * 100 / maximum)));
}
try {
java.lang.Thread.sleep(100L);
} catch (java.lang.InterruptedException ex) {
ex.printStackTrace();
}
} while (value == null || value.intValue() < jpb.getMaximum());
}
}
在你的框架类中使用 progressBar
和这样的新类
and in your frame class use progressBar
with the new class like this
ProgressBarUpdator ju = new ProgressBarUpdator(progressBar);
new java.lang.Thread(ju).start();
无论何时您想更改值,只需使用语句
Whenever you want to change the value just use the statement
ju.setValue([Value to set]);
这篇关于进度条 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!