I'm trying to use threads to run a lenghty operation in the background and update the UI. Here's what i'm trying to do:
- on a button click, display a popupjframe with a message "Inserting into DB"
- create a new thread to insert 1000s of entries into a database.
- when the entries are inserted, i want the popupjframe to disappear and display a joptionpane with yes, no buttons
- on clicking the yes button i want to display another frame with a report/details about the insertion process
Here's my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//display popupframe first
jFrame1.pack();
jFrame1.setVisible(true);
jFrame1.setLocationRelativeTo(getFrame());
Thread queryThread = new Thread() {
public void run() {
runQueries();
}};
queryThread.start();
}
//runqueries method inserts into DB
private v开发者_如何学JAVAoid runQueries() {
for (int i = 0; i <= 50000; i++) {
insertintoDB();
updateProgress(i);
}
}
//update the popupjframe
private void updateProgress(final int queryNo) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (queryNo == 50000) { //means insertion is done
jFrame1.setVisible(false);
int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION);
if (n == 1) { //NO option was selected
return;}
else
//display another popupframe with details/report of inserting process
}});
}
- Is my approach correct??
- How and when do i stop/interrupt the "queryThread"??
- Is it correct if i make the popupjframe in the runqueries method itself (after the for loop) and display the joptionpane??
Thanks in advance.
Look at the documentation for SwingWorker. It does exactly what you are trying to do. Create a subclass, and call runQueries from doInBackground(), and then do what your runnable does (minus the if queryNo check) in done(). There are third party versions of this class if you are not using java 1.6.
class DbSwingWorker extends SwingWorker<Void, Integer> {
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i <= 50000; i++) {
insertintoDB();
publish(i); //if you want to do some sort of progress update
}
return null;
}
@Override
protected void done() {
int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION);
if (n == 1) { //NO option was selected
return;
} else {
//display another popupframe with details/report of inserting process
}
}
}
The original, non-1.6 version can be found here: https://swingworker.dev.java.net/
精彩评论