Está en la página 1de 17

"Trucos Java Swing

jCheckBox
No hacer binding de checkbox

y validar el valor if (jCheckBox1.isSelected()) { usuario1.setActivo(true); } else { usuario1.setActivo(false); } Podemos indicar si esta seleccionado por defecto

StringTokenizer
Se utiliza para descomponer una cadena en tokens String linea = "panama,cuba,espaa"; String pais; StringTokenizer elementos; elementos = new StringTokenizer(linea, ","); while (elementos.hasMoreTokens()) { pais = elementos.nextToken(); }

Tablas JTable

Arrastrar un JTable o JXTable a un formulario Ajustamos el diseno

Arrastramos el beans y el controller. Definimos variables DefaultTableModel modelo; int fila = -1; Ahora en el init modelo = (DefaultTableModel) jXTable1.getModel(); try { if (usuariosController1.Listar()) { Object[] columna = new Object[3]; // Hay tres columnas en la tabla for (Usuarios u : usuariosController1.getUsuarioslist()) { columna[0] = u.getCedula(); columna[1] = u.getNombre(); modelo.addRow(columna); } } } catch (Exception ex) { Mensajeria.MensajeError(ex, "Tablas()"); }

Hacer JTable ordenable por columnas


TableRowSorter<TableModel> ordenacion = new TableRowSorter<TableModel>(modeloHittingLocal); jTableHittingLocal.setRowSorter(ordenacion);

Ajustar el tamao de columnas en un JTable


TableColumn columnId = jXTable1.getColumnModel().getColumn(2); columnId.setPreferredWidth(60);

Eliminar Todas las filas de un JTable


if(modelo != null){ while (modelo.getRowCount() > 0) { modelo.removeRow(0); } }

Si queremos eliminar filas, basados en seleccin de registros


Si deseamos eliminar ciertos registros de un jTable, en una de las columnas la definimos como booleanos, de manera que aparezca una casilla de seleccin. En este ejemplo asumimos que la casilla de seleccin est en la columna 0. Le pasamos al mtodo el modelo y el nmero de columna donde est la casilla. En el botn eliminar int pos; while(true){

pos = PosicionMarcado(modeloHittingLocal,0); if(pos != -1){ modeloHittingLocal.removeRow(pos); }else{ break; } } // El mtodo que elimina los registros // Obtenemos el valor que esta en la casilla. private Integer PosicionMarcado(DefaultTableModel lmodelo, int columna){ try{ for(int fila= 0; fila<lmodelo.getRowCount();fila++){ if(lmodelo.getValueAt(fila,columna).equals(true)){ return fila; } } }catch(Exception ex){ Mensajeria.MensajeError(ex, "PosicionMarcado()"); } return -1; }

Seleccionar todos jcheckbok de un jtable


try { SeleccionarTodo(modeloHittingLocal, 0); } catch (Exception ex) { Mensajeria.MensajeError(ex, "Agregar()"); } // metodo private void SeleccionarTodo(DefaultTableModel lmodelo, int columna) { try { for (int fila = 0; fila < lmodelo.getRowCount(); fila++) { lmodelo.setValueAt(true, fila, columna); } } catch (Exception ex) { Mensajeria.MensajeError(ex, "SeleccionarTodo()"); } }

Deseleccionar todas las filas en la columna con jcheckbox


private void DeSeleccionarTodo(DefaultTableModel lmodelo, int columna) { try { for (int fila = 0; fila < lmodelo.getRowCount(); fila++) { lmodelo.setValueAt(false, fila, columna); } } catch (Exception ex) { Mensajeria.MensajeError(ex, "SeleccionarTodo()"); } }

Recorrer la Tabla
int n = jTable1.getRowCount(); if (n == 0) { Mensajeria.Mensaje("No existe ninguna fila en la tabla"); return; } String cedula; String nombre; for (int i = 0; i < n; i++) { cedula = jTable1.getValueAt(i, 0).toString(); nombre = jTable1.getValueAt(i, 1).toString(); }

Ajustar el tamao de las columnas automaticamente


Recorremos las columnas con un for y le indicamos el tamao deseado. En el ejemplo recorre desde la columna 4 hasta el final y le asigna un tamao de 60 for (int i = 4; i < jTableHittingVisitante.getColumnCount(); i++) { TableColumn column = jTableHittingVisitante.getColumnModel().getColumn(i); column.setPreferredWidth(60); }

Order columnas en el JTable


TableRowSorter<TableModel> elQueOrdena = new TableRowSorter<TableModel> (modeloHittingLocal); jTableHittingLocal.setRowSorter(elQueOrdena);

Referencia: http://chuwiki.chuidiang.org/index.php?title=JTable:_Ordenar_y_filtrar_filas

Actualizar columna de la tabla


for (int i = 0; i < n; i++) { cedula = jTable1.getValueAt(i, 0).toString(); nombre = jTable1.getValueAt(i, 1).toString(); nombre="Mr " +nombre; jTable1.setValueAt(nombre, i, 1); }

Eventos a nivel de fila y agregar un men en JTable


1. Definimos los objetos

JPopupMenu popupMenu = new JPopupMenu("Menu"); JMenuItem menu1= new JMenuItem("Opcion 1"); JSeparator separator0 = new javax.swing.JSeparator(); JMenuItem menuCerrar = new JMenuItem("Cerrar"); int fila;
2. En el evento init

TableColumn column = jTable1.getColumnModel().getColumn(0); column.setPreferredWidth(30); column.setCellEditor(new DefaultCellEditor(comboRumboLatitud)); comboRumboLatitud.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ComboAction(evt); } }); /* * Action del menu */ menu1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); menuCerrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // jMenuItemCerrarctionPerformed(evt); } }); popupMenu.add(menu1); popupMenu.add(separator0); popupMenu.add(menuCerrar); TableColumn columnPopup = jTable1.getColumnModel().getColumn(1); this.jTable1.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { popupMenu.show(jTable1, e.getX(), e.getY()); } fila = jTable1.rowAtPoint(e.getPoint()); int columna = jTable1.columnAtPoint(e.getPoint()); if ((fila > -1) && (columna > -1)) { String valorColumna = String.valueOf(jTable1.getValueAt(fila, 1)); } } }); //Creamos los eventos private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { try { String valor = String.valueOf(jTable1.getValueAt(fila, 1)); JOptionPane.showMessageDialog(this, valor); } catch (Exception ex) { } }

Eventos de una Columna de un JTable


1. Definir un objeto

JTextField fieldGrados; int filas;


2. En el init del formulario

fieldGrados = new JTextField(); fieldGrados.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldGradosActionPerformed(evt); } }); TableColumn column = jTable1.getColumnModel().getColumn(3); column.setCellEditor(new DefaultCellEditor(fieldGrados)); column.setPreferredWidth(80);
3. Crear el mtodo

private void jTextFieldGradosActionPerformed(java.awt.event.ActionEvent evt) { try { String tmp = this.fieldGrados.getText(); if (tmp == null || tmp.equals("")) { return; } fila = jTable1.getSelectedRow(); if (fila == -1) { JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE); return; } Procesar(); } catch (Exception ex) { } }
4. Crear el mtodo procesar

private void Procesar() { try { if (fila == -1) { JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE); return; } String Numero = String.valueOf(jTable1.getValueAt(fila, 0)); if (Numero == null || Numero.equals("")) { Mensajeria.Mensaje("Ingrese el numero"); return; } Integer newVal = Integer.parseInt(Numero) * 2; jTable1.setValueAt(newVal, fila, 1);

} catch (Exception ex) { Mensajeria.MensajeError(ex, "Procesar()"); } }

Agregar un Combo a un JTable


1. Definir el objeto JComboBox comboRumboLatitud; int filas; 2. En el init del formulario

comboRumboLatitud = new JComboBox(); comboRumboLatitud.addItem("NE"); comboRumboLatitud.addItem("NW"); comboRumboLatitud.addItem("SE"); comboRumboLatitud.addItem("SW"); comboRumboLatitud.setSelectedItem("NE"); TableColumn column = jTable1.getColumnModel().getColumn(0); column.setPreferredWidth(30); column.setCellEditor(new DefaultCellEditor(comboRumboLatitud)); comboRumboLatitud.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ComboAction(evt); } });
3. Crear el mtodo

private void ComboAction(java.awt.event.ActionEvent evt) { try { filas = jTable1.getSelectedRow(); if (filas == -1) { JOptionPane.showMessageDialog(this, "No se selecciono ninguna fila", "Mensaje", JOptionPane.WARNING_MESSAGE); return; } String sel = comboRumboLatitud.getSelectedItem().toString(); JOptionPane.showMessageDialog(this, sel); } catch (Exception ex) { } }

Manejo de Fechas

0. Agregar el JDatePicker al formulario 1. Crear una instancia del calendario

java.util.Calendar ca = java.util.Calendar.getInstance();
2. Obtener la fecha actual

java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());


3. Asignarla a jXDatePicker

jXDatePickerFechaNacimiento.setDate(mydate);
4. Establecer el formato para la fecha

jXDatePickerFechaNacimiento.setFormats(new SimpleDateFormat("dd/MM/yyyy"));
5. Obtener el ao mes y dia

int year = ca.get(java.util.Calendar.YEAR); this.Anio = year; int nmes = ca.get(java.util.Calendar.MONTH);

Obtener El ao de una fecha en una tabla


Date date = rs.getDate("fecha"); SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy"); Integer anio = Integer.parseInt(simpleDateformat.format(date));

6. Validar fecha seleccionada


java.util.Date Fecha = jXDatePickerFechaNacimiento.getDate(); java.sql.Date fechaNacimiento = new java.sql.Date(Fecha.getTime()); if (fechaNacimiento == null) { Mensajeria.Mensaje("Seleccione la fecha de nacimiento"); jXDatePickerFechaNacimiento.requestFocus(); return; } empleado1.setFechanacimiento(fechaNacimiento);

7. Formatear la fecha para mostrarla en un jTable


for (Acuerdos a : acuerdosController1.getAcuerdoslist()) { Format formatter; formatter = new SimpleDateFormat("dd/MM/yyyy"); Date fecha = a.getFecha(); String MyFecha = formatter.format(fecha); filas[2] = MyFecha; }

Otro ejemplo de formateo de fechas


SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");

props.setProperty("fecha", formateador.format(new Date()));

Integrando iReport
Para integrar iReport , debemos realizar los siguientes pasos

1. Descargar el plugin para NetBeans desde http://jasperforge.org/project/ireport 1.1 Instalamos el plugin

Manipulando List<>
//Definimos los List List<String> ListaIdSubGrupo = new ArrayList<String>(); List<Double> ListaTotalSubGrupo = new ArrayList<Double>(); //Removemos todos los elementos if(ListaIdSubGrupo != null){ ListaIdSubGrupo.removeAll(ListaIdSubGrupo); } //Agregar ListaIdSubGrupo.add("hola"); ListaIdSubGrupo.add("adios");

ListaIdSubGrupo.add("nada"); //Remover un elemento ListaIdSubGrupo.remove("adios"); //Recorrer la lista for (int i = 0; i < ListaIdSubGrupo().size(); i++) { System.out.println(" "+ ListaIdSubGrupo.get(i); } //Otra forma de recorrer la lista for(String s:ListaIdSubGrupo()){ System.out.println(" "+s); }

List de clases
List<MyInformeDiarioSubgrupo> listMyInformeDiariosubgrupo = new ArrayList<MyInformeDiarioSubgrupo>();

Actualizar una clase dentro de la List


for (int i = 0; i < listMyInformeDiariosubgrupo.size(); i++) { if(listMyInformeDiariosubgrupo.get(i).getCodigo().equals(idsubgruporecargo)){ listMyInformeDiariosubgrupo.get(i).setPago(listMyInformeDiariosubgrupo.get(i).get Pago() + recibosdetalles.getPago()); } }

Campos Formateados
Arrastramos de la paleta un jFormattedTextField y luego damos clic derecho y seleccionamos Personalizar Codigo. Agregamos MaskFormatter mask = null; try{ mask = new MaskFormatter("###.#.#.##.##.##.##"); }catch(Exception ex){ } //cambiamos a codigo personalizado para editar y colocamos el mask jFormattedTextField1 = new javax.swing.JFormattedTextField(mask);

Formatear Decimales
En la clase de SesionLocal static DecimalFormat formateador = new DecimalFormat("###########.##"); public static DecimalFormat getFormateador() { return formateador; } public static void setFormateador(DecimalFormat formateador) { SesionLocal.formateador = formateador; }
En las otras clases

jTextFieldTotalRecaudado.setText(SesionLocal.getFormateador().format(granTotal) );

SubString
Devuelve una cadena substring(indice_inicial, indice_final -1) Ejemplo: String texto="561.2.8."; String t = texto(0,3) // devuelve 561 t = texto(4,5);//devuelve 2 t = texto(6,7);//devuelve 8

StringBuilder
//definir StringBuilder sb = new StringBuilder(""); //agregar sb.append("\nHola"); //eliminar sb.delete(0, sb.length());

Archivo de Propiedades
Podemos utilizar archivos de propiedades, para ello lo agregamos en la seccin de archivos del proyecto.

Cdigo private void Leer() { Properties props = new Properties(); String myversion = "0.01"; try { props.load(new FileInputStream("versiones.properties")); myversion = props.getProperty("version"); } catch (IOException ex) { Mensajeria.MensajeError(ex, "Leyendo archivo propiedades()"); } if (myversion == null) { //el archivo no existe o no tiene la propiedad sesion myversion = "0.0"; } else { } } /* *

*/ private void EscribirActualizar() { try { Properties props = new Properties(); props.setProperty("version", "0.34"); props.store(new FileOutputStream("versiones.properties",false),""); System.out.println(" grabado o actualizado...."); } catch (Exception ex) { System.out.println(" " + ex); } } Cuando generamos el jar del proyecto, tambien tenemos que copiar el archivo de propiedades.

Leer Archivo de Propiedades de un jar con ResourceBundle


Definimos un objeto ResourceBundle y utilizamos el metodo getString() para obtener las propiedades ResourceBundle rb = ResourceBundle.getBundle("org.gemaapi.properties.configuration"); this.proyecto = rb.getString("proyecto"); this.username = rb.getString("username");

Cambiar un JFrame por JInternalFrame en NetBeans


Si anteriormente creamos un JFrame en NetBeans y desamos cambiarlo por un JInternalFrame, el proceso es muy sencillo. 1. Cambiar la definicin de la clase public class ActividadCrear extends javax.swing.JFrame { //por public class ActividadCrear extends javax.swing.JInternalFrame { 2. Comentar o eliminar // public static void main(String args[]) { // java.awt.EventQueue.invokeLater(new Runnable() { // // public void run() { // try { // new ActividadCrear().setVisible(true); // } catch (ParseException ex) { // //Logger.getLogger(ActividadCrear.class.getName()).log(Level.SEVERE, null, ex); // }

// // //

} }); }

3. En el menu principal 3.1 Agregar un jDesktopPanel al formulario principal 3.2 Evento jMenuItem ActividadCrear actividadCrear = new ActividadCrear(); //para centrar el JInternalFrame Toolkit tk = Toolkit.getDefaultToolkit(); Dimension screenSize = tk.getScreenSize(); int screenHeight = screenSize.height; int screenWidth = screenSize.width; actividadCrear.setLocation((int) (screenWidth / 2.8), (int) (screenHeight / 4)); actividadCrear.setVisible(true); jDesktopPane1.add(actividadCrear);

JXTipOfTheDay
Podemos indicar los tips para mostrar

Definimos los objetos JXTipOfTheDay tipOfTheDay = new JXTipOfTheDay(loadModel()); private static TipOfTheDayModel loadModel() { List tips = Arrays.asList(new DefaultTip("Tip 1", "Este proceso importa grupo, subgrupo, regimen de la base de datos de ingresos"), new DefaultTip("Tip 2", "Este proceso consume mucho tiempo.")); DefaultTipOfTheDayModel model = new DefaultTipOfTheDayModel(tips); return model;

} Para mostrarlo usamos tipOfTheDay.showDialog(this); Referencias http://www.eclipsezone.com/eclipse/forums/t55436.html

JXStatusBar
Podemos utilizar la barra de estado. Pasos: 1. Arrastramos el componente a al diseador 2. Creamos un JLabel para actualizar los mensajes JLabel statusLabel = new JLabel(); 3.En el init del formulario agregar jXStatusBar1.add(statusLabel); 4. En el boton agregar Thread queryThread = new Thread() { public void run() { runQueries(); } }; queryThread.start(); 5. Crear el metodo runQueries() private void runQueries() { for (int i = 0; i < noQueries; i++) { runDatabaseQuery(i); updateProgress(i); } } 6. Crear el metodo para actualizar el JLabel private void updateProgress(final int queryNo) { SwingUtilities.invokeLater(new Runnable() { public void run() { statusLabel.setText("Query: " + queryNo); } }); }

También podría gustarte