Java - ¿Cómo cancelar un SwingWorked?

 
Vista:

¿Cómo cancelar un SwingWorked?

Publicado por Elalio (1 intervención) el 23/09/2016 23:40:16
Hola Buenas tardes a todos.
Tengo un problema con mi programa; estoy utilizado un swingworked para leer los registros de la base de datos y simular que lo carga con un JProgressBar.
Tengo un boton de inicio que hace la simulación de carga (Esto lo hace correctamente) y sin problemas.
Pero cuando intento detener el swingworked para que no siga con el ciclo de leer la informacion, no termina.
Se que un SwingWorked se cancela o termina con "swk.cancel(true);" pero no logro detenerlo.
Agredezco mucho su orientacion para lograr resolver mi problema.
Muchas gracias

Este es mi código

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import java.io.Serializable;
 
/**
 * @author elalio
 *
 */
public final class ControlEntradas implements Serializable {
 
	public ControlEntradas() {
	}
 
	/**
	 * @param id_entrada
	 * @param id_usuario
	 * @param ip_maquina
	 * @param nombre_so
	 * @param version_k
	 * @param tipo
	 * @param version_jdk
	 * @param version_db
	 */
	public ControlEntradas(int id_entrada, int id_usuario,
			String ip_maquina, String nombre_so, String version_k,
			String tipo, String version_jdk, String version_db) {
		this.id_entrada = id_entrada;
		this.id_usuario = id_usuario;
		this.ip_maquina = ip_maquina;
		this.nombre_so = nombre_so;
		this.version_k = version_k;
		this.tipo = tipo;
		this.version_jdk = version_jdk;
		this.version_db = version_db;
	}
 
 
	/**
	 * @return the id_entrada
	 */
	public int getId_entrada() {
		return id_entrada;
	}
	/**
	 * @param id_entrada the id_entrada to set
	 */
	public void setId_entrada(int id_entrada) {
		this.id_entrada = id_entrada;
	}
	/**
	 * @return the id_usuario
	 */
	public int getId_usuario() {
		return id_usuario;
	}
	/**
	 * @param id_usuario the id_usuario to set
	 */
	public void setId_usuario(int id_usuario) {
		this.id_usuario = id_usuario;
	}
	/**
	 * @return the ip_maquina
	 */
	public String getIp_maquina() {
		return ip_maquina;
	}
	/**
	 * @param ip_maquina the ip_maquina to set
	 */
	public void setIp_maquina(String ip_maquina) {
		this.ip_maquina = ip_maquina;
	}
	/**
	 * @return the nombre_so
	 */
	public String getNombre_so() {
		return nombre_so;
	}
	/**
	 * @param nombre_so the nombre_so to set
	 */
	public void setNombre_so(String nombre_so) {
		this.nombre_so = nombre_so;
	}
	/**
	 * @return the version_k
	 */
	public String getVersion_k() {
		return version_k;
	}
	/**
	 * @param version_k the version_k to set
	 */
	public void setVersion_k(String version_k) {
		this.version_k = version_k;
	}
	/**
	 * @return the tipo
	 */
	public String getTipo() {
		return tipo;
	}
	/**
	 * @param tipo the tipo to set
	 */
	public void setTipo(String tipo) {
		this.tipo = tipo;
	}
	/**
	 * @return the version_jdk
	 */
	public String getVersion_jdk() {
		return version_jdk;
	}
	/**
	 * @param version_jdk the version_jdk to set
	 */
	public void setVersion_jdk(String version_jdk) {
		this.version_jdk = version_jdk;
	}
	/**
	 * @return the version_db
	 */
	public String getVersion_db() {
		return version_db;
	}
	/**
	 * @param version_db the version_db to set
	 */
	public void setVersion_db(String version_db) {
		this.version_db = version_db;
	}
 
 
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id_entrada;
		result = prime * result + id_usuario;
		result = prime * result + ((ip_maquina == null) ? 0 : ip_maquina.hashCode());
		result = prime * result + ((nombre_so == null) ? 0 : nombre_so.hashCode());
		result = prime * result + ((tipo == null) ? 0 : tipo.hashCode());
		result = prime * result + ((version_db == null) ? 0 : version_db.hashCode());
		result = prime * result + ((version_jdk == null) ? 0 : version_jdk.hashCode());
		result = prime * result + ((version_k == null) ? 0 : version_k.hashCode());
		return result;
	}
 
 
	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof ControlEntradas)) {
			return false;
		}
		ControlEntradas other = (ControlEntradas) obj;
		if (id_entrada != other.id_entrada) {
			return false;
		}
		if (id_usuario != other.id_usuario) {
			return false;
		}
		if (ip_maquina == null) {
			if (other.ip_maquina != null) {
				return false;
			}
		} else if (!ip_maquina.equals(other.ip_maquina)) {
			return false;
		}
		if (nombre_so == null) {
			if (other.nombre_so != null) {
				return false;
			}
		} else if (!nombre_so.equals(other.nombre_so)) {
			return false;
		}
		if (tipo == null) {
			if (other.tipo != null) {
				return false;
			}
		} else if (!tipo.equals(other.tipo)) {
			return false;
		}
		if (version_db == null) {
			if (other.version_db != null) {
				return false;
			}
		} else if (!version_db.equals(other.version_db)) {
			return false;
		}
		if (version_jdk == null) {
			if (other.version_jdk != null) {
				return false;
			}
		} else if (!version_jdk.equals(other.version_jdk)) {
			return false;
		}
		if (version_k == null) {
			if (other.version_k != null) {
				return false;
			}
		} else if (!version_k.equals(other.version_k)) {
			return false;
		}
		return true;
	}
 
	/**
	 * 
	 */
	private static final long serialVersionUID = -1004110771863112909L;
	private int id_entrada;
	private int id_usuario;
	private String ip_maquina;
	private String nombre_so;
	private String version_k;
	private String tipo;
	private String version_jdk;
	private String version_db;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 * @author elalio
 *
 */
public final class MuestraEntradas implements Serializable {
 
	public static ArrayList<ControlEntradas> obtenEntradas() {
		try {
			listaControl = new ArrayList<>();
			conx = ConectaDB.obtenerConexion();
			pstm = conx.prepareStatement(CONSULTA);
			result = pstm.executeQuery();
			while (result.next()) {
				id_entradas = result.getInt(1);
				id_usuarios = result.getInt(2);
				ip_maquinas = result.getString(3);
				nombre_sos = result.getString(4);
				version_ks = result.getString(5);
				tipos = result.getString(6);
				version_jdks = result.getString(7);
				version_dbs = result.getString(8);
				listaControl.add(new ControlEntradas(id_entradas, id_usuarios, ip_maquinas, nombre_sos, version_ks,
						tipos, version_jdks, version_dbs));
			}
			if (!listaControl.isEmpty() && listaControl.size() != 0) {
				System.out.println("La tabla tiene valores");
				return listaControl;
			} else {
				System.out.println("No hay datos");
				return null;
			}
		} catch (SQLException e) {
			// TODO: handle exception
			for (Throwable ex : e) {
				System.out.printf("Error------------------->%s%n", ex.getLocalizedMessage());
			}
			return null;
		} finally {
			if (pstm != null) {
				try {
					pstm.close();
				} catch (SQLException e) {
					// TODO: handle exception
					for (Throwable ex : e) {
						System.out.printf("Error------------------->%s%n", ex.getLocalizedMessage());
					}
				}
			}
			if (result != null) {
				try {
					result.close();
				} catch (SQLException e) {
					// TODO: handle exception
					for (Throwable ex : e) {
						System.out.printf("Error------------------->%s%n", ex.getLocalizedMessage());
					}
				}
			}
			if (conx != null) {
				ConectaDB.cerrarConexion(conx);
			}
		}
	}
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 3802376295249310174L;
	private static Connection conx;
	private static PreparedStatement pstm;
	private static ResultSet result;
	private static ArrayList<ControlEntradas> listaControl;
	private static final String CONSULTA = "SELECT id_entrada,id_usuario,ip_maquina,"
			+ "nombre_so,version_k,tipo,version_jdk,version_db FROM control_entradas";
	private static int id_entradas;
	private static int id_usuarios;
	private static String ip_maquinas;
	private static String nombre_sos;
	private static String version_ks;
	private static String tipos;
	private static String version_jdks;
	private static String version_dbs;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
 * @author elalio
 *
 */
public final class BackgroundWorker extends SwingWorker<Void, Void> {
 
	/**
	 * 
	 */
	public BackgroundWorker(JButton btn, JProgressBar barras) {
		btns = btn;
		barraProgreso = barras;
		listaEntradas = MuestraEntradas.obtenEntradas();
		// TODO Auto-generated constructor stub
		addPropertyChangeListener(e -> {
			barraProgreso.setValue(getProgress());
		});
	}
 
	@Override
	protected Void doInBackground() throws Exception {
		// TODO Auto-generated method stub
		while (!isCancelled()) {
			System.out.println(isCancelled() + "---------------------------------------------------------------------------------\n" +
		"--------------------------------------------------------------------------------------------------------------------------");
			total = listaEntradas.size();
			listaEntradas.forEach(l -> {
				System.out.println("Id de entrada: " + l.getId_entrada() + " Id usuario: " + l.getId_usuario() + " IP: "
						+ l.getIp_maquina() + " SO: " + l.getNombre_so() + " Kernel: " + l.getVersion_k()
						+ " Tipo de usuario: " + l.getTipo() + " Jdk: " + l.getVersion_jdk()
						+ " Versión base de datos: " + l.getVersion_db());
				setProgress((int) (((i++) * 100) / total) + 1);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.printf("Error------------------->%s%n", e.getLocalizedMessage());
				}
			});
		}
		return null;
	}
 
	@Override
	public void done() {
		Toolkit.getDefaultToolkit().beep();
		btns.setEnabled(true);
		barraProgreso.setValue(0);
		setProgress(0);
		System.out.println("Terminado");
		System.out.println("Total de registros: " + listaEntradas.size());
		showMessageDialog(null, "Se han cargado todos los registros", "Monitor", INFORMATION_MESSAGE);
 
	}
 
	private ArrayList<ControlEntradas> listaEntradas;
	private int total, i = 0;
	private JButton btns;
	private JProgressBar barraProgreso;
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * @author elalio
 *
 */
public class UIControl extends JFrame {
 
	public UIControl() {
		// TODO Auto-generated constructor stub
		super("Probando barra de progreso");
		con = getContentPane();
		con.setLayout(new GridLayout(4, 0));
		eti = new JLabel("Empezando con JProgressBar");
		barra = new JProgressBar();
		barra.setStringPainted(true);
		barra.setMinimum(MIN);
		barra.setMaximum(MAX);
		botonAcciona = new JButton("Inicia");
		botonAcciona.addActionListener(e -> {
			EventQueue.invokeLater(() -> {
				if (!Iniciado) {
					botonAcciona.setEnabled(false);
					new BackgroundWorker(botonAcciona, barra).execute();
					Iniciado = false;
				}
			});
		});
		botonCancela = new JButton("Cancelar");
		botonCancela.addActionListener(e -> {
			EventQueue.invokeLater(() -> {
				new BackgroundWorker(botonAcciona, barra).cancel(true);
			});
		});
		con.add(eti);
		con.add(barra);
		con.add(botonAcciona);
		con.add(botonCancela);
		setSize(new Dimension(ANCHURA, ALTURA));
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		repaint();
		revalidate();
	}
 
	/**
	 * 
	 */
	private static final long serialVersionUID = 7499538122632982906L;
	private final Container con;
	private final JLabel eti;
	private final JButton botonAcciona, botonCancela;
	private final JProgressBar barra;
	private static final int MIN = 0, MAX = 100, ANCHURA = 300, ALTURA = 100;
	private boolean Iniciado = false;
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder