Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
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()"); }
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; }
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(); }
Referencia: http://chuwiki.chuidiang.org/index.php?title=JTable:_Ordenar_y_filtrar_filas
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) { } }
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);
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
java.util.Calendar ca = java.util.Calendar.getInstance();
2. Obtener la fecha actual
jXDatePickerFechaNacimiento.setDate(mydate);
4. Establecer el formato para la fecha
jXDatePickerFechaNacimiento.setFormats(new SimpleDateFormat("dd/MM/yyyy"));
5. Obtener el ao mes y dia
Integrando iReport
Para integrar iReport , debemos realizar los siguientes pasos
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>();
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.
// // //
} }); }
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;
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); } }); }