Hoy aprenderemos como crear una barra de carga mientras realizamos alguna acción (Llenado de una tabla, una consulta a la base, cargar una imagen, etc.)
Para lograr esto se requiere el manejo de un hilo, en este caso por seguridad y practicidad usaremos SwingWorker, que es un hilo precisamente creado para manejar este tipo de eventos y evitarnos conflictos con los hilos del Event Dispatcher en swing (No importa si no has entendido mucho solo ten en cuenta que SwingWorker es un hilo)
De aquí en adelante la explicación viene en el código, específicamente en el método simularAlgo este es realmente quien hace todo. Por ultimo sepan que este ejemplo lo cree con NetBeans así que quienes quieran descargar el source para editarlo visualmente pueden hacerlo, los que no pues copien y peguen. Les dejo una imagen del ejemplo como referencia
Update: Si les marca error en el import org.jdesktop.application.Action; Descarguen el Jar aquí y agréguenlo al proyecto
Para lograr esto se requiere el manejo de un hilo, en este caso por seguridad y practicidad usaremos SwingWorker, que es un hilo precisamente creado para manejar este tipo de eventos y evitarnos conflictos con los hilos del Event Dispatcher en swing (No importa si no has entendido mucho solo ten en cuenta que SwingWorker es un hilo)
De aquí en adelante la explicación viene en el código, específicamente en el método simularAlgo este es realmente quien hace todo. Por ultimo sepan que este ejemplo lo cree con NetBeans así que quienes quieran descargar el source para editarlo visualmente pueden hacerlo, los que no pues copien y peguen. Les dejo una imagen del ejemplo como referencia
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.jdesktop.application.Action;
/**
*
* @JaverosAnonimos
*/
public class JFrameCarga extends javax.swing.JFrame {
//Indica el valor maximo de las barras de carga
private int maximo=1000;
/** Creates new form JFrameCarga */
public JFrameCarga() {
initComponents();
}
@SuppressWarnings("unchecked")
//
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jbPrueba = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jtaPrueba = new javax.swing.JTextArea();
jpbPruebaDer = new javax.swing.JProgressBar();
jpbPruebaIzq = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("www.JaverosAnonimos.tk");
jPanel1.setName("jPanel1"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(JFrameCarga.class, this);
jbPrueba.setAction(actionMap.get("simularAlgo")); // NOI18N
jbPrueba.setText("Simular Algo");
jbPrueba.setName("jbPrueba"); // NOI18N
jScrollPane1.setName("jScrollPane1"); // NOI18N
jtaPrueba.setColumns(20);
jtaPrueba.setRows(5);
jtaPrueba.setName("jtaPrueba"); // NOI18N
jScrollPane1.setViewportView(jtaPrueba);
jpbPruebaDer.setMaximum(10000);
jpbPruebaDer.setName("jpbPruebaDer"); // NOI18N
jpbPruebaDer.setStringPainted(true);
jpbPruebaIzq.setMaximum(10000);
jpbPruebaIzq.setName("jpbPruebaIzq"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE)
.addComponent(jbPrueba)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jpbPruebaIzq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
.addComponent(jpbPruebaDer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jbPrueba)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jpbPruebaDer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jpbPruebaIzq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 570, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 443, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}//
@Action
public void simularAlgo() {
final SwingWorker worker = new SwingWorker() {
@Override
protected Void doInBackground() throws Exception {
try {
//Ponemos los valores máximos a las barras
jpbPruebaDer.setMaximum(maximo);
jpbPruebaIzq.setMaximum(maximo);
//Con esto hacemos que la barra de carga no tenga porcentaje y se convierta indeterminada
jpbPruebaIzq.setIndeterminate(true);
//Aquí iría el código de la acción, en este caso un ejemplo sencillo
for (int i = 0; i < maximo; i++) {
//Vamos agregando el valor a la barra para mostrarlo en el porcentaje
jpbPruebaDer.setValue(i);
//Escribimos un mensaje en el area te texto
jtaPrueba.append("Simulando... "+i+"\n");
jtaPrueba.setCaretPosition(jtaPrueba.getText().length()-1);
//Damos un poco de tiempo durmiendo el hilo 2 milisegundos entre cada ciclo
Thread.currentThread().sleep(2);
}
JOptionPane.showMessageDialog(null, "Termino");
//Aquí terminaría la acción
//Quitamos esta propiedad para que deja de animarse la barra
jpbPruebaIzq.setIndeterminate(false);
//Reseteamos el valor de la barra que tiene porcentaje
jpbPruebaDer.setValue(0);
}catch (Exception ex) {
System.out.println(ex);
}
return null;
}
};
worker.execute();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrameCarga().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton jbPrueba;
private javax.swing.JProgressBar jpbPruebaDer;
private javax.swing.JProgressBar jpbPruebaIzq;
private javax.swing.JTextArea jtaPrueba;
// End of variables declaration
}
Update: Si les marca error en el import org.jdesktop.application.Action; Descarguen el Jar aquí y agréguenlo al proyecto
hola amigo no funciona
ResponderBorrarimport org.jdesktop.application.Action;
esta linea me sale error y no encuentro como colocarlo me ayudas porfavor?
Que tal!
ResponderBorrarTe falta agregar el Jar del AppFramework Ya actualice el post en la parte de hasta abajo esta el link de descarga
Saludoss!
Fa que fenomeno! me costo encontrar un ejemplo práctico de swingWorker, muchas gracias! Saludos desde uruguay
ResponderBorrarQue tal!
ResponderBorrarQue bien que te sirvio
Saludos desde Mèxico
oye.... renueva los enlaces porfas por que no se puede deskargar ñ_ñ
ResponderBorrarGracias!!!!
Gracias! estaba atascado entre heredar de JPanel y Swingworker, muy practico
ResponderBorrarQue bueno que te sirvió! Saludos.
BorrarGracias, me sirvió tu ejemplo.
ResponderBorrarno aparece tu enlace de descarga
ResponderBorrarPublicar un comentario