Esto complementa al tutorial
Uso de swingworker en una aplicacion
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * FrmProductos.java * * Created on 18-oct-2010, 14:14:27 */ package miaplicacion.ui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import miaplicacion.util.ArraylistTableModel; /** * * @author dinfantas */ public class FrmProductos extends javax.swing.JInternalFrame { private java.sql.Connection con; /** Creates new form FrmProductos */ public FrmProductos() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") //private void initComponents() { jbtnListar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jtblProductos = new javax.swing.JTable(); progressBar = new javax.swing.JProgressBar(); setClosable(true); setIconifiable(true); setMaximizable(true); setTitle("Productos"); jbtnListar.setText("Listar"); jbtnListar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnListarActionPerformed(evt); } }); jtblProductos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jtblProductos); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jbtnListar) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)) .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jbtnListar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// private void jbtnListarActionPerformed(java.awt.event.ActionEvent evt) { //iniciamos nuestra barra de progreso progressBar.setValue(0); //Definimos nuestro Query final String query = "select * from APP.PRODUCT"; //vamos a crear nuestra conexion a la BD conectar(); final javax.swing.SwingWorker worker = new javax.swing.SwingWorker() { //donde almacenaremos los datos ArraylistTableModel model; ArrayList datos; String[] cols = new String[8];//son 8 columnas @Override protected Void doInBackground() throws Exception { datos = new ArrayList();//instanciamos try { //Creamos un Statement para ejecutar el query java.sql.PreparedStatement pstmt = con.prepareStatement(query); //ejecutamos el query pstmt.executeQuery(); // asignamos el resutaldo a rs java.sql.ResultSet rs = pstmt.getResultSet(); //asignamos la metadata java.sql.ResultSetMetaData rm = rs.getMetaData(); //creamos un array donde pondremos los nombres de columnas for (int i = 0; i < rm.getColumnCount(); i++) { cols[i] = rm.getColumnName(i+1).toString(); } //recorremos el Resultset while (rs.next()) {//mientras halla datos ArrayList fila = new ArrayList();//instanciamos donde almacenaremos los datos de cada fila for (int i = 1; i <= rm.getColumnCount(); i++) { fila.add(rs.getObject(i).toString()); } datos.add(fila);//agregamos la fila cargada setProgress(datos.size());//actualizamos el progreso } } catch (SQLException ex) { Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex); } return null; } @Override protected void done() { setProgress(100); jtblProductos.setModel(new ArraylistTableModel(datos, cols)); } }; worker.addPropertyChangeListener(new PropertyChangeListener() {//agregarmos un escuchador de cambio de propiedad public void propertyChange(PropertyChangeEvent pce) { progressBar.setValue(worker.getProgress());//actualizamos el valor del progressBar } }); worker.execute(); } // Variables declaration - do not modify private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbtnListar; private javax.swing.JTable jtblProductos; private javax.swing.JProgressBar progressBar; // End of variables declaration private void conectar() { try { Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); String dbUrl = "jdbc:derby://localhost:1527/sample";//URL DE CONEXION A LA DB con = DriverManager.getConnection(dbUrl,"app","app"); } catch (InstantiationException ex) { Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(FrmProductos.class.getName()).log(Level.SEVERE, null, ex); } } }
No hay comentarios:
Publicar un comentario