在我的 Java GUI 应用程序中,我有一个JButton
,单击时它调用 afunction
连接到 a database
,然后调用 afunction
中的clear
a ,然后调用从一个文件读取文本并加载的 a,它调用从另一个文件读取文本的 a,比较来自两者,然后调用数据库中的一个或数据,所有这些都可以正常工作。table
DB
function
variables
function
data
function
update
insert
但是我的问题与 相关JButton
,当它被点击时,我想运行一个Indeterminate progress bar
,这样用户就知道工作正在完成,然后在它离开之前并将action listener setIndeterminate to false
值设置progress bar
为100(complete)
,但在我的情况下,当你点击button
它时停留在单击状态并progress bar
冻结。
我应该采取什么措施来防止这种情况?线程可能?但我对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());
}
}