I'm new to Java Swing, and I need to make some simple Java desktop app. I have MainPanel in which I have SwingWorker with doInBackgroung in which I call service which calls a DAO that make a quering data from database.
I also have a stop button which on click set worker.cancel(true), but the program is not stopping, and I can not even close the window with the [X] button.
I suppose that the processing is not stopped immediately because the querying of the database is not done yet, but why can't I close the window?
This is the code:
worker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
long startTime = System.nanoTime();
textArea.append("Starting...\n");
generatingFilesService.genereteFiles(connectionDBFirst, connectionDBSecond, connectionDBThird,
date1, date2);
long endTime = System.nanoTime();
double time = (double) ((endTime - startTime) / 1_000_000_000);
if (ConnectionDBFirst.flag != false) {
if (time < 60d) {
textArea.append("Genereting ended for " + time + " seconds\n");
textArea.setCaretPosition(MainPanel.textArea.getDocument().getLength());
} else {
textArea.append("Genereting ended for " + (time / 60) + " minutes\n");
textArea.setCaretPosition(MainPanel.textArea.getDocument().getLength());
}
}
return null;
}
@Override
protected void done() {
if (isCancelled()) {
textArea.append("Stopping generating files...\n");
closeConnections();
logger.info(Messages.PROCESS_INTERUPTED);
} else
closeConnections();
}
};worker.execute();
Stopping code:
if (e.getSource() == stop) {
worker.cancel(true);
stop.setEnabled(false);
}
UPDATE
Based on the answer and comments, here is the rest of the code:
public void genereteFiles(connectionDBFirst, connectionDBSecond, connectionDBThird,
date1, date2) {
List persons1 = daoFirst.getPersons(connectionDBFirst, date1, date2);
// Here I want to update the textArea() that the daoFirst.getPersons() is done
// but how to that without MainPanel.textArea.append(...);
List persons2 = daoSecond.getPersons(connectionDBSecond, date1, date2);
// Here I want to update the textArea() that the daoSecond.getPersons() is done
// but how to that without MainPanel.textArea.append(...);
// same with daoThird
genereteFilesService.createFiles(persons1, persons2, persons3);
// update textArea() again
}
DAO code:
public List getPersons(connectionDBFirst, date1, date2) {
// Executing SQL query and getting the persons
// This takes long time, and from here I calculate
// percentage of persons fetched and I want to show the percentage in textArea()
// but how to do that without MainPanel.textArea.append(...);
}
Now, beside initial question, how can I use publish() and process() methods to update the textArea() from generateFiles() and DAO methods?