How can I stop the SwingWorker
doing his work? I know there's the cancel()
method for that, but the most I could do is to anonymously create a new SwingWorker
that is doing the job.
Here is the code for reference:
public void mostrarResultado(final ResultSet resultado) {
new SwingWorker<Void, Object[]>() {
@Override
public Void doInBackground() {
// TODO: Process ResultSet and create Rows. Call publish() for every N rows created.+
DefaultTableModel modelo = new DefaultTableModel();
jTableResultados.removeAll();
int columnas;
int res = 0;
try {
ResultSetMetaData metadata = resultado.getMetaData();
columnas = metadata.getColumnCount();
Object[] etiquetas = new Object[columnas];
jProgressBar.setIndeterminate(true);
for (int i = 0; i < columnas; i++) {
etiquetas[i] =
metadata.getColumnName(i + 1);
}
modelo.setColumnIdentifiers(etiquetas);
jTableResultados.setModel(modelo);
while (resultado.next() && !this.isCancelled()) {
res++;
Object fila[] = new Object[columnas];
for (int i = 0; i < columnas; i++) {
fila[i] = resultado.getObject(i + 1);
}
modelo.addRow(fila);
publish(fila);
}
jProgressBar.setIndeterminate(false);
if (res == 0) {
JOptionPane.showMessageDialog(jPanelClientes.getParent(), "No se encontraron resultados con los criterios de búsqueda definidos", "Sin resultados", JOptionPane.INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "Excepcion: ", ex);
JOptionPane.showMessageDialog(jPanelClientes.getParent(), "Error en al ejecutar la busqueda seleccionada", "Error", JOptionPane.ERROR_MESSAGE);
}
return null;
}
}.execute();
}
Actually the job is well done and published with no issues, but given that I work with a DB, it can happen that the query has too many results and the time taken for the full publish takes a time so the user has to be able to cancel the task and run a new one.
Obviously the worker is a different method than the cancel button event so I won't be able to invoke Worker cancel()
method.
Tried making the worker an attribute for the class with no luck this way:
public class myClass extends javax.swing.JFrame {
private SwingWorker<Void, Object[]> tarea;
but then when I go for:
tarea = new SwingWorker<Void,Object[]>(){...}
I get Incompatible types, found void, required SwingWorker, and I'm totally out of ideas.
Any tips?
Thanks