Reputation: 87
the data included in a jList's model, gets updated from a swingworker. the problem is that I subclassed the SwingWorker class in an independent *.java file. So I can't access the GUI components (in this case, the model and the jList). In fact i think it's better not to put this subclass in the JFrame form, to avoid it being a mess, but that's the only way I can figure out to make it work. If I put this subclass in the jframe form, i guess I could update the model and the Jlist using the done() method of the swingworker abstract class.
but is there any way to access the GUI components (jList & model) from the swingworker, when the swingWorker is in another *.java file?
I call the swingworker here using INVOKE LATER. right after i try to update the models, but it seems that it doesn't wait for the swingworker to end its job, so when it updates the model, the swingworker hasn't finished yet, so the data is not updated yet.
as you can see in the next piece of code, i also tried to put the update code in an INVOKE LATER after the first one, but it doesn't seem to synchronize either.
private void jMenuItem2MousePressed(java.awt.event.MouseEvent evt) {
// BOTON DESCARGAR DATOS DEL SERVIDOR OPCION DEL MENU
File filePref = new File("preferencias.config");
if (filePref.exists()) {
int n = JOptionPane.showConfirmDialog(
this, "¿Está seguro de que desea descargar todos los datos del servidor"
+ " (datos e imágenes)a local? Todos los datos locales serán reemplazados"
+ " y no se podrán recuperar.",
"Confirmación de descarga",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
// *** THIS invokeLater() calls the SwingWorker subclass to update the data
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
DescargarDatosDelServidor.createAndShowGUI();
}
});
// *** THIS invokeLater() updates the model and the jList
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// BORRAMOS MODELO DE LOS JList
modelo.clear();
modelo2.clear();
modelo3.clear();
// AGREGAMOS ELEMENTOS AL MODELO Y
// SETEAMOS EL MODELO EN LAS JList
// seguros
for (int i = 0; i < AlmacenSeguros.getInstance().getListaSeguros().size(); i++) {
modelo.addElement(AlmacenSeguros.getInstance().getListaSeguros().get(i));
}
jList_seguros.setModel(modelo);
// gestoria
for (int i = 0; i < AlmacenGestoria.getInstance().getListaGestoria().size(); i++) {
modelo2.addElement(AlmacenGestoria.getInstance().getListaGestoria().get(i));
}
jList_gestoria1.setModel(modelo2);
// consultoria
for (int i = 0; i < AlmacenConsultoria.getInstance().getListaConsultoria().size(); i++) {
modelo3.addElement(AlmacenConsultoria.getInstance().getListaConsultoria().get(i));
}
jList_consultoria.setModel(modelo3);
}
});
} else if (n == JOptionPane.NO_OPTION) {
}
} else {
// PREFERENCIAS SERVIDOR FTP
JTextField jTF_dirFTP = new JTextField();
JTextField jTF_usrFTP = new JTextField();
JPasswordField jTF_pssFTP = new JPasswordField();
final JComponent[] inputs = new JComponent[]{
new JLabel("Direccion del Servidor FTP"),
jTF_dirFTP,
new JLabel("Nombre de Usuario FTP"),
jTF_usrFTP,
new JLabel("Password de Usuario FTP"),
jTF_pssFTP
};
// seteamos jTF
jTF_dirFTP.setText(AlmacenPreferencias.getInstance().preferencias.getDirFTP());
jTF_usrFTP.setText(AlmacenPreferencias.getInstance().preferencias.getUsrFTP());
jTF_pssFTP.setText(AlmacenPreferencias.getInstance().preferencias.getPssFTP());
JOptionPane.showMessageDialog(null, inputs, "Preferencias del Servidor FTP", JOptionPane.PLAIN_MESSAGE);
AlmacenPreferencias.getInstance().preferencias.setDirFTP(jTF_dirFTP.getText());
AlmacenPreferencias.getInstance().preferencias.setUsrFTP(jTF_usrFTP.getText());
AlmacenPreferencias.getInstance().preferencias.setPssFTP(new String(jTF_pssFTP.getPassword()));
AlmacenPreferencias.getInstance().guardarPreferencias();
}
}
so I wonder how can I get this to work. I hope I explained myself properly.
I also read about the RUNANDWAIT() method, but it seems you can't call it from the EDT. so... I'm kind of lost right now. I'm quite newbie so have mercy in your comments ;)
thanks in advance!!
THE CLASS WHERE THE SWINGWORKER IS:
public class DescargarDatosDelServidor extends JPanel implements PropertyChangeListener {
private JProgressBar progressBar;
private JTextArea taskOutput;
private Task task;
private static JFrame frame;
private String taskOutputString;
InputStream is = null;
FileOutputStream fos = null;
final String AbsolutePath = new File(".").getAbsolutePath();
final String imagesPath = AbsolutePath.substring(0, AbsolutePath.length() - 1);
class Task extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() {
String ftpDir = AlmacenPreferencias.getInstance().preferencias.getDirFTP();
String ftpUsr = AlmacenPreferencias.getInstance().preferencias.getUsrFTP();
String ftpPwd = AlmacenPreferencias.getInstance().preferencias.getPssFTP();
// DESCARGAR IMAGENES
taskOutputString = "de las imagenes del servidor descargadas\n";
int progress = 0;
setProgress(0);
FTPClient cliente1 = new FTPClient();
try {
cliente1.connect(ftpDir);
cliente1.login(ftpUsr, ftpPwd);
cliente1.enterLocalPassiveMode();
cliente1.setFileType(FTP.BINARY_FILE_TYPE);
cliente1.changeWorkingDirectory("html/androidlyc/imagenes");
FTPFile[] ftpFiles = cliente1.listFiles();
if (ftpFiles != null && ftpFiles.length > 0) {
//loop thru files
for (FTPFile file : ftpFiles) {
if (!file.isFile()) {
continue;
}
System.out.println("File is " + file.getName());
// descargar imagen
String dir = "imagenes";
File dirFile = new File(dir);
boolean existe = dirFile.mkdir();
File fileFile = new File(dirFile, file.getName());
fos = new FileOutputStream(fileFile);
cliente1.retrieveFile(file.getName(), fos);
// actualizamos progreso
progress += (100 / (ftpFiles.length));
setProgress(Math.min(progress, 100));
}
}
fos.close();
cliente1.logout();
cliente1.disconnect();
} catch (IOException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
}
//
//
// DESCARGAR seguros.XML
//
// Borrar datos de local
AlmacenSeguros.getInstance().getListaSeguros().clear();
AlmacenGestoria.getInstance().getListaGestoria().clear();
AlmacenConsultoria.getInstance().getListaConsultoria().clear();
File fileSegCheck1 = new File("seguros.dat");
File fileSegCheck2 = new File("gestoria.dat");
File fileSegCheck3 = new File("consultoria.dat");
if (fileSegCheck1.exists()) {
fileSegCheck1.delete();
}
if (fileSegCheck2.exists()) {
fileSegCheck2.delete();
}
if (fileSegCheck3.exists()) {
fileSegCheck3.delete();
}
//
// PARSEAR SEGUROS
//
taskOutputString = "de los datos de SEGUROS del servidor descargados\n";
progress = 0;
setProgress(0);
FTPClient cliente2 = new FTPClient();
try {
cliente2.connect(ftpDir);
cliente2.login(ftpUsr, ftpPwd);
cliente2.enterLocalPassiveMode();
cliente2.setFileType(FTP.BINARY_FILE_TYPE);
cliente2.changeWorkingDirectory("/html/androidlyc");
fos = new FileOutputStream("seguros.xml");
cliente2.retrieveFile("seguros.xml", fos);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File fileXML = new File("seguros.xml");
Document document = builder.parse(fileXML);
Element root = document.getDocumentElement();
NodeList items = root.getElementsByTagName("seguro");
for (int i = 0; i < items.getLength(); i++) {
Seguro seguroActual = new Seguro();
Node item = items.item(i);
NodeList datosSeguro = item.getChildNodes();
for (int j = 0; j < datosSeguro.getLength(); j++) {
Node dato = datosSeguro.item(j);
String etiqueta = dato.getNodeName();
if (etiqueta.equals("seg_tipo")) {
seguroActual.setSeg_tipo(dato.getTextContent());
} else if (etiqueta.equals("seg_subtipo")) {
seguroActual.setSeg_subtipo(dato.getTextContent());
} else if (etiqueta.equals("seg_title")) {
seguroActual.setSeg_title(dato.getTextContent());
} else if (etiqueta.equals("seg_descr")) {
seguroActual.setSeg_descr(dato.getTextContent());
} else if (etiqueta.equals("seg_carac_title")) {
seguroActual.setSeg_carac_title(dato.getTextContent());
} else if (etiqueta.equals("seg_carac")) {
seguroActual.setSeg_carac(dato.getTextContent());
} else if (etiqueta.equals("seg_cober_title")) {
seguroActual.setSeg_cober_title(dato.getTextContent());
} else if (etiqueta.equals("seg_cober")) {
seguroActual.setSeg_cober(dato.getTextContent());
} else if (etiqueta.equals("seg_pack_title1")) {
seguroActual.setSeg_pack_title1(dato.getTextContent());
} else if (etiqueta.equals("seg_pack1")) {
seguroActual.setSeg_pack1(dato.getTextContent());
} else if (etiqueta.equals("seg_pack_title2")) {
seguroActual.setSeg_pack_title2(dato.getTextContent());
} else if (etiqueta.equals("seg_pack2")) {
seguroActual.setSeg_pack2(dato.getTextContent());
} else if (etiqueta.equals("seg_pack_title3")) {
seguroActual.setSeg_pack_title3(dato.getTextContent());
} else if (etiqueta.equals("seg_pack3")) {
seguroActual.setSeg_pack3(dato.getTextContent());
} else if (etiqueta.equals("seg_pack_title4")) {
seguroActual.setSeg_pack_title4(dato.getTextContent());
} else if (etiqueta.equals("seg_pack4")) {
seguroActual.setSeg_pack4(dato.getTextContent());
} else if (etiqueta.equals("seg_pack_title5")) {
seguroActual.setSeg_pack_title5(dato.getTextContent());
} else if (etiqueta.equals("seg_pack5")) {
seguroActual.setSeg_pack5(dato.getTextContent());
} else if (etiqueta.equals("seg_imagen_url")) {
seguroActual.setSeg_imagen_url(dato.getTextContent());
}
seguroActual.setSeg_imagen_loc(imagesPath + "imagenes\\" + seguroActual.getSeg_imagen_url());
}
AlmacenSeguros.getInstance().guardarSeguro(seguroActual);
// actualizamos progreso
progress += (100 / (items.getLength()));
setProgress(Math.min(progress, 100));
}
fos.close();
cliente2.logout();
cliente2.disconnect();
} catch (IOException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
}
//
// PARSEAR GESTORIA
//
taskOutputString = "de los datos de GESTORIA del servidor descargados\n";
progress = 0;
setProgress(0);
try {
DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
DocumentBuilder builder2 = factory2.newDocumentBuilder();
File fileXML = new File("seguros.xml");
Document document2 = builder2.parse(fileXML);
Element root2 = document2.getDocumentElement();
NodeList items2 = root2.getElementsByTagName("gestoria");
for (int i = 0; i < items2.getLength(); i++) {
Gestoria gestoriaActual = new Gestoria();
Node item2 = items2.item(i);
NodeList datosGestoria = item2.getChildNodes();
for (int j = 0; j < datosGestoria.getLength(); j++) {
Node dato2 = datosGestoria.item(j);
String etiqueta2 = dato2.getNodeName();
if (etiqueta2.equals("ges_title")) {
gestoriaActual.setGes_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_area01_title")) {
gestoriaActual.setGes_area01_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv01_title")) {
gestoriaActual.setGes_serv01_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv01")) {
gestoriaActual.setGes_serv01(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota01_title")) {
gestoriaActual.setGes_cuota01_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota01")) {
gestoriaActual.setGes_cuota01(dato2.getTextContent());
} else if (etiqueta2.equals("ges_area02_title")) {
gestoriaActual.setGes_area02_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv02_title")) {
gestoriaActual.setGes_serv02_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv02")) {
gestoriaActual.setGes_serv02(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota02_title")) {
gestoriaActual.setGes_cuota02_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota02")) {
gestoriaActual.setGes_cuota02(dato2.getTextContent());
} else if (etiqueta2.equals("ges_area03_title")) {
gestoriaActual.setGes_area03_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv03_title")) {
gestoriaActual.setGes_serv03_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_serv03")) {
gestoriaActual.setGes_serv03(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota03_title")) {
gestoriaActual.setGes_cuota03_title(dato2.getTextContent());
} else if (etiqueta2.equals("ges_cuota03")) {
gestoriaActual.setGes_cuota03(dato2.getTextContent());
} else if (etiqueta2.equals("ges_imagen_url")) {
gestoriaActual.setGes_imagen_url(dato2.getTextContent());
}
gestoriaActual.setGes_imagen_loc(imagesPath + "imagenes\\" + gestoriaActual.getGes_imagen_url());
}
AlmacenGestoria.getInstance().guardarGestoria(gestoriaActual);
// actualizamos progreso
progress += (100 / (items2.getLength()));
setProgress(Math.min(progress, 100));
}
} catch (IOException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
}
//
// PARSEAR CONSULTORIA
//
taskOutputString = "de los datos de CONSULTORIA del servidor descargados\n";
progress = 0;
setProgress(0);
try {
DocumentBuilderFactory factory3 = DocumentBuilderFactory.newInstance();
DocumentBuilder builder3 = factory3.newDocumentBuilder();
File fileXML = new File("seguros.xml");
Document document3 = builder3.parse(fileXML);
Element root3 = document3.getDocumentElement();
NodeList items3 = root3.getElementsByTagName("consultoria");
for (int i = 0; i < items3.getLength(); i++) {
Consultoria consultoriaActual = new Consultoria();
Node item3 = items3.item(i);
NodeList datosConsultoria = item3.getChildNodes();
for (int j = 0; j < datosConsultoria.getLength(); j++) {
Node dato3 = datosConsultoria.item(j);
String etiqueta3 = dato3.getNodeName();
if (etiqueta3.equals("con_title")) {
consultoriaActual.setCon_title(dato3.getTextContent());
} else if (etiqueta3.equals("con_resumen")) {
consultoriaActual.setCon_resumen(dato3.getTextContent());
} else if (etiqueta3.equals("con_texto")) {
consultoriaActual.setCon_texto(dato3.getTextContent());
} else if (etiqueta3.equals("con_imagen_url")) {
consultoriaActual.setCon_imagen_url(dato3.getTextContent());
}
consultoriaActual.setCon_imagen_loc(imagesPath + "imagenes\\" + consultoriaActual.getCon_imagen_url());
}
AlmacenConsultoria.getInstance().guardarConsultoria(consultoriaActual);
// actualizamos progreso
progress += (100 / (items3.getLength()));
setProgress(Math.min(progress, 100));
}
} catch (IOException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(DescargarDatosDelServidor.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// @Override
// protected void process(List<Void> list) {
// super.process(list); //To change body of generated methods, choose Tools | Templates.
// }
@Override
protected void done() {
frame.dispose();
JOptionPane.showMessageDialog(null, "Todos los datos del servidor han sido descargados en local.", "Descargar datos", JOptionPane.PLAIN_MESSAGE);
}
}
public DescargarDatosDelServidor() {
super(new BorderLayout());
// Create the demo's UI.
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressBar.setPreferredSize(new Dimension(500, 30));
taskOutput = new JTextArea(10, 40);
taskOutput.setMargin(new Insets(5, 5, 5, 5));
taskOutput.setEditable(false);
JPanel panel = new JPanel();
panel.add(progressBar, BorderLayout.NORTH);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("progress")) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format("%d%% " + taskOutputString, task
.getProgress()));
}
}
public static void createAndShowGUI() {
// Create and set up the window.
frame = new JFrame("Descargando datos del servidor...");
//frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new DescargarDatosDelServidor();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
frame.setAlwaysOnTop(true);
}
}
Upvotes: 0
Views: 662
Reputation: 205825
Give your worker access to the view component's model. Changes to its model will update the listening JList
. In this example, the model is referenced from an enclosing class, but you can pass a reference to the worker's constructor.
Addendum: How do I give the worker access to the JList
model?_
Given the following worker declaration, for example, pass the ListModel
as a parameter in a suitable constructor and update the model in your implementation of process()
:
class MyTask extends SwingWorker<List<…>, …> {
MyTask(ListModel model) {
…
}
}
Upvotes: 2