在我的
Java GUI应用程序中,我有一个JButton,当点击它调用一个函数来连接数据库,然后调用一个函数来清除数据库中的表,然后调用一个函数从一个文件中读取文本并加载变量,这些函数调用从另一个文件中读取文本的函数,比较两者中的数据,然后调用函数来更新或插入数据库中的数据,所有这些都可以正常工作.
但是我的问题与JButton有关,当它点击时我想运行一个Indeterminate进度条,这样用户就知道正在完成工作,然后就在它将动作监听器setIndeterminate保留为false并设置进度条的值之前到100(完成),但在我的情况下,当您单击按钮时,它保持在单击状态,进度条冻结.
我应该实施什么来防止这种情况?可能穿线?但我对java中的线程很新.这是我的动作听众:
private class buttonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
dbConnect(); //connects to DB
clearSchedules(); // deletes data in tables
readFile(); // reads first file and calls the other functions
dbClose();// closes the DB
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}
}
}
另外,我希望操作栏实际上随着程序的进展而移动,但我不确定如何监控其进度.
谢谢,牛肉.
这里更新是我的SwingWorker示例以及我如何使用它:
全球宣布
private functionWorker task;
private abstract class functionWorker extends SwingWorker {
public void execute() {
try {
dbConnect();
} catch (SQLException e) {
e.printStackTrace();
}
clearSchedules();
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
dbClose();
}
}
在我的actionPerformed方法中
if( e.getSource() == genButton )
{
progressBar.setIndeterminate(true);
progressBar.setString(null);
try
{
task.execute();
progressBar.setIndeterminate(false);
progressBar.setValue(100);
}
catch (Exception e1){
System.err.println("Error: " + e1.getMessage());
}
}