当我处理一些数据库表时,我有一个ProgressMonitor
显示。一开始不知道表的数量,所以我创建ProgressMonitor
了最大值为 100 的表。
一旦在SwingWorker
线程中开始处理,它就会获取表数并将最大值设置ProgressMonitor
为表数(在我的测试中约为 530)。但是,ProgressMonitor
即使最大值增加并且进度条准确显示 100/530,仍然会在 100 处结束并停止线程的执行。
知道为什么会这样吗?
从按钮按下actionListener
启动ProgressMonitor
和SwingWorker
(名为TaskThread):
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals("generate")) {
progressMonitor = new ProgressMonitor(this, "Generating...", "", 0, 100);
task = new TaskThread();
task.addPropertyChangeListener(this);
task.execute();
genButton.setEnabled(false);
}
}
PropertyChangeListener
更新ProgressMonitor
:
public void propertyChange(PropertyChangeEvent evt)
{
if ("progress" == evt.getPropertyName() )
{
int progress = (Integer) evt.getNewValue();
progressMonitor.setProgress(progress);
String message = String.format("Completed %d%%.\n", progress);
progressMonitor.setNote(message);
if (progressMonitor.isCanceled() || task.isDone())
{
Toolkit.getDefaultToolkit().beep();
if (progressMonitor.isCanceled()) {
task.cancel(true);
}
genButton.setEnabled(true);
}
}
}
SwingWorker
班级:
class TaskThread extends SwingWorker<Void, Void>
{
@Override
public Void doInBackground()
{
String tableList = tablesArea.getText().trim();
script = "";
String filename = outPath.getText
// Connect to Database
Connection conn = getDbConnection();
if (conn == null)
return null;
try {
// if tableList is blank, get all tables from the From Database afm_tbls table
if (tableList.equals(""))
{
// code omitted
}
}
catch (SQLException se) {
canWriteFile = false;
handleError(se);
}
String[] tables = tableList.split(",");
generateRecordCount(conn, tables);
// Close the connection
if(conn != null)
{
try {
conn.close();
}
catch (Exception ignored) {}
}
// Write SQL code to a file
writeScript(filename);
return null;
}
private void generateRecordCount(Connection conn, String[] tables)
{
setProgressMax(tables.length);
setProgress(0);
// Loop through tables
for (int i = 0; i < tables.length; i++)
{
// Get record count for each table
try {
String sql = "SELECT COUNT(*) AS reccount FROM " + tables[i];
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(sql);
rs.next();
int recCount = rs.getInt("reccount");
if (recCount > 0)
script += tables[i] + ": " + recCount + nl;
// Set progress of SwingWorker, ProgressMonitor is updated by PropertyChangeListener
int prog = getProgress() + 1;
setProgress(prog);
}
catch(SQLException se)
{
handleError(se);
}
}
}
}