sábado, 5 de mayo de 2012

Cambiar color de las filas de una tabal (Jtable) en Java

En esta entrada os voy a comentar como hacer para cambiar los colores de las filas de un JTable en función de un valor o del valor de varios argumentos o celdas que vosotros queráis. Es algo realmente sencillo, ya veréis que con tan solo apenas 20 líneas de código se puede hacer... En este caso vamos a hacer que la tabla tenga las filas azules cuando el usuario este ACTIVO y que la fila esté roja cuando el usuario esté INACTIVO.

Me salto el paso de cómo crear la tabla ya que sino me va a quedar un código bastante amplio. Si alguien necesita que le diga como hacer una Tabla, ya sea con datos desde un archivo, desde BD, nada más que tiene que preguntarmelo.

Vamos allá.

Con la tabla montada, tenemos que hacer lo siguiente:

TablaClientes.setDefaultRenderer(Object.class, new FormatoTablaClientes());


Con esto estamos asignando un nuevo render a nuestra tabla. Para ello nos creamos una nueva clase FormatoTablaClientes que herede (extends) de DefaultTableCellRenderer.

El contenido de esta clase que hereda de DefaultTableCellRenderer es el siguiente:




import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class FormatoTablaUsuarios extends DefaultTableCellRenderer
{
public Component getTableCellRendererComponent
(JTable table, Object value, boolean selected, boolean focused, int row, int column)
{
        // SI EN CADA FILA DE LA TABLA LA CELDA 5 ES IGUAL A ACTIVO COLOR AZUL
if(String.valueOf(table.getValueAt(row,5)).equals("ACTIVO"))  setForeground(Color.blue);
                // SI NO ES ACTIVO ENTONCES COLOR ROJO
else  setForeground(Color.red);

super.getTableCellRendererComponent(table, value, selected, focused, row, column);
return this;
}
}




Si queremos que sea solamente el color de una celda, pues en este caso, solamente la celda de ACTIVO o INACTIVO deberíamos poner:   if(String.valueOf(table.getValueAt(row,column)).equals("ACTIVO"))

Podemos jugar con lo siguiente:

isSelected -> Si se selecciona la fila, columna, celda, etc... cambiar de color.
focused -> Si se ha hecho el foco sobre algo cambiar el color.

Y todo lo que se os ocurra.

Espero que os haya servido de ayuda y si tenéis cualquier duda sólo tenéis que preguntar :)

Un saludo.

viernes, 4 de mayo de 2012

Imprimir JTable directamente eligiendo impresora.


En esta entrada os voy a poner un ejemplo de como imprimir una Tabla en vuestra impresora directamente, es muy sencillo así que no tiene muchas florituras. 

La salida por la impresora será Un encabezado, la tabla en el cuerpo de la hoja y en el pie el número de página. 

public class Principal {
private static JButton btImprimir;

public static void main(String[] args) {
try {
 UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException e) {
 e.printStackTrace();
} catch (InstantiationException e) {
 e.printStackTrace();
} catch (IllegalAccessException e) {
 e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
 e.printStackTrace();
}
JFrame v = new JFrame();
v.setBounds(0,0,835,360);
v.setLayout(null);
v.setVisible(true);
v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final String [] columnas = {"NOMBRE", "APELLIDOS", "DNI", "ESTADO", "BLOQUEO", "ALTA"};
    
final DefaultTableModel dtm = new DefaultTableModel();
final JTable tabla1 = new JTable(dtm);
tabla1.setUpdateSelectionOnSort(true);
for (int i=0; i<6; i++){
dtm.addColumn(columnas[i]);
}
tabla1.setPreferredScrollableViewportSize(new Dimension(800,200));
JScrollPane scrollPane = new JScrollPane(tabla1);
v.add(scrollPane);
scrollPane.setBounds(10,10,800,200);
final Object [] fila2 = {"Carlos", "Mateo Ruiz", "71024121F", "ACTIVO", "0", "2012/02/02"};
final Object [] fila3 = {"Marta", "Perez Hidalgo", "29116227H", "ACTIVO", "1", "2010/21/10"};
dtm.addRow(fila2);
dtm.addRow(fila3);
btImprimir = new JButton("IMPRIMIR");
btImprimir.setBounds(10, 250, 120, 25);
v.add(btImprimir);
btImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
        
                      try {
       
       
           // tabla1.print();//envia los datos de la tabla a la impresora
                 
                  MessageFormat headerFormat = new MessageFormat("Listado de Clientes 2010-2012);
                  MessageFormat footerFormat = new MessageFormat("- Página {0} -");
                  tabla.print(PrintMode.FIT_WIDTH, headerFormat, footerFormat);
                                   
                 
         } catch (PrinterException ex) {
             JOptionPane.showMessageDialog(null, "No se ha podido imprimir correctamente, intentalo más tarde.");
         }                 
                
            }
            
            
        });
v.repaint();
}

miércoles, 25 de abril de 2012

Jugando un poco con fechas


Bueno en esta entrada voy a poner como pasar un String a Date y con ese formato intentar hacer sumas de días, meses, o cualquier otro tipo de operación.


Ahí va el código:



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JOptionPane;


public class TestFechas {

//VARIABLES
private static Date fecha_DATE;
private static String fecha_STRING;


public static void main(String[] args) {

/* STRING QUE EXTRAEMOS DE UN TXT, BD O CUALQUIERA OTRA FUENTE
               EN ESTE CASO LA PONGO MANUAL PARA SER MAS DIRECTO*/

fecha_STRING = "2011-02-28 01:50:52";



/*ESTABLECER FORMATO AÑO-MES-DIA HORA:MINUTOS:SEGUNDOS (TAMBIEN SE PUEDE MILISEGUNDOS)*/

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");



try {

// PARSEO STRING A DATE
fecha_DATE = sdf.parse(fecha_STRING);
} catch (ParseException e) {

System.out.println("Se ha producido un error de parseo");
}

//MOSTRAR STRING INICIAL
System.out.println("Fecha String: \t\t\t" + fecha_STRING + "\n");

//MOSTRAR TRAS PARSEO A DATE
System.out.println("Date: \t\t\t\t\t" + fecha_DATE + "\n");


//INSTANCIA DE CALENDARIO
Calendar c = Calendar.getInstance();

//ESTABLECEMOS LA FECHA DEL CALENDARIO CON EL DATE GENERADO ANTERIORMENTE
  c.setTime(fecha_DATE);
 
/*** OPERACIONES QUE PODEMOS HACER CON CALENDARIO
PODEMOS SUMAR, RESTAR DIAS, MESES, AÑOS...
PODEMOS COMPARAR SI ES ANTERIOR, RECIENTE, ETC..

// SUMAMOS 1 DIA AL CALENDARIO
    c.add(Calendar.DATE, 1);
 
// CONVERTIMOS CALENDARIO A DATE
      fecha_DATE = c.getTime();    

//MOSTRAMOS DATE FINAL
  System.out.println("Date Anterior con 1 día sumado: \t" + fecha_DATE);

}

viernes, 13 de abril de 2012

jueves, 22 de marzo de 2012

String a Date (Fecha) en Java





Buenas a tod@s!

Con esta entrada os quiero enseñar como se puede paar de String a date (fecha). ¿Para qué lo podemos necesitar? El ejemplo que más se me viene a la cabeza y por el cual tuve que investigar y por lo tanto puede que vosotros también es cuando cogía datos de tipo datetime o smalldatetime en sql server y lo recogía como string en java y luego quería tratar con él como si fuera de formato fecha.

Normalmente cualquier SGBD tendra un tipo de datos datetime, date o smalldatetime.

El tipo datetime suele ser así: "12/08/2012 12:51:12" si esta almacenado en formato local español.


Bueno en mi programa ejemplo voy a aplicarlo directamente sobre un String, pero como ya he dicho antes lo cogeríamos por ejemplo de una Base de Datos y lo almacenaríamos como string, con lo cual es lo mismo.

El código sería el siguiente:


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class principal {

public static void main(String[] args) {
String fecha = "12/08/2012 12:51:12";
Date d = null;
/* FORMATOS EN EL CUAL QUEREMOS LA FECHA EN
EN ESTE CASO DIA / MES / AÑO */
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
try {
//parseamos string a tipo date
d = sdf.parse(fecha);
} catch (ParseException e) {
e.printStackTrace();
}

//ALGUNOS TIPOS DE FORMATOS
DateFormat dfDateShort = DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println(dfDateShort.format(d));
//FORMATO MEDIO
DateFormat dfDateMedium = DateFormat.getDateInstance(DateFormat.MEDIUM);
System.out.println(dfDateMedium.format(d));
//FORMATO NORMAL
DateFormat dfDefault = DateFormat.getInstance();
System.out.println(dfDefault.format(d));
}

}


Ese es el pequeño código... Hay muchos más formatos, para verlos todos solamente necesitaremos por DateFormat.#Estilo_que_queramos, ya sea Long, milisegundos, decadas, short...

Espero que os haya servido de ayuda y cualquier duda o comentario nada más tenéis que postearlo e intentaré ayudaros.

¡Un saludo!

domingo, 18 de marzo de 2012

Un poco de JSplitPane y JScrollPane


La misma implementación que hice en la entra anterior, pero en vez de 3 JInternalFrame he usado 3 paneles (JPanel) con Scroll y Split.


public class VentanaPrincipal extends JFrame{ public VentanaPrincipal(){ { this.setTitle("Ventana Principal"); Container contenido = this.getContentPane(); crearJToolBar(); contenido.add(barraJTool, BorderLayout.NORTH); //CREAR PANELES PanelIzquierdo pi = new PanelIzquierdo(); pi.setBackground(Color.WHITE); PanelCentral pc= new PanelCentral(); pc.setBackground(Color.LIGHT_GRAY); PanelSuperior ps = new PanelSuperior(pc); ps.setBackground(Color.LIGHT_GRAY); scrollPI = new JScrollPane(); scrollPI.getViewport().add(pi, null); scrollPS = new JScrollPane(); scrollPS.getViewport().add(ps, null); Dimension d= new Dimension(800, 150); scrollPS.setMinimumSize(d); scrollPC = new JScrollPane(); scrollPC.getViewport().add(pc, null); jSP_1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,scrollPS,scrollPC); jSP_2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scrollPI,jSP_1); jSP_1.setOneTouchExpandable(true); jSP_2.setOneTouchExpandable(true); } }


Espero que les haya servido de ayuda y para lo que sea dejen un comentario.

Un saludo.
 
     

viernes, 16 de marzo de 2012

Escritorio con 3 ventanas internas dinámicas


Bueno te cuento...

VentanaPrincipal es JFRAME es la ventana principal.

En la ventana principal se alojan 3 JInternalFrames, Izquierdo, Superior y central.

Ahí va el código:


VENTANA PRINCIPAL (JFRAME): [CODE]public class VentanaPrincipal extends JFrame { private VentanaPrincipal vp; private PanelCentral pc; private PanelSuperior ps; private PanelIzquierdo pi; public VentanaPrincipal(){ this.setLayout(null); this.setTitle("VENTANA PRINCIPAL"); this.setResizable(true); this.setBounds(0, 0, 1024, 768); this.setLocationRelativeTo(null); vp=this; /******** PANEL CENTRAL *******************/ pc = new PanelCentral(); /******** PANEL SUPERIOR *******************/ ps = new PanelSuperior(this, pc); /******** PANEL IZQUIERDO *******************/ pi = new PanelIzquierdo(this,ps,pc); ps.setPanelIzquierdo(pi); /******** AÑADIR A LA VENTANA *******************/ add(pi); add(pc); add(ps); /******** ESCUCHADOR CUANDO CAMBIAMOS TAMAÑO DE VENTANA PRINCIPAL *******************/ this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { pi.setBounds(0, 30, 200, vp.getHeight()-72); pc.setBounds(pi.getWidth(),ps.getHeight()+30,vp.getWidth()-pi.getWidth()-18,vp.getHeight()-ps.getHeight()-72); ps.setBounds(pi.getWidth(),30,vp.getWidth()-pi.getWidth()-18,vp.getHeight()-pc.getHeight()-70); } }); } public static String getFechaActual() { Date ahora = new Date(); SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy"); return formateador.format(ahora); } public static String getHoraActual() { Date ahora = new Date(); SimpleDateFormat formateador = new SimpleDateFormat("hh:mm:ss"); return formateador.format(ahora); } }[/CODE] PANEL CENTRAL: [CODE]public class PanelCentral extends JInternalFrame { private int x, y; private PanelCentral pc; private JScrollPane scrollPane; public PanelCentral(){ pc=this; this.setLayout(null); this.setTitle(null); this.setVisible(true); this.setClosable(false); this.setMaximizable(false); this.setResizable(false); } }[/CODE] PANEL SUPERIOR [CODE] public class PanelSuperior extends JInternalFrame implements ComponentListener { private PanelIzquierdo vpi; private VentanaPrincipal vvp; private PanelSuperior vps; private PanelCentral vpc; public PanelSuperior(VentanaPrincipal vp, PanelCentral vc){ vps=this; vvp=vp; vpc=vc; this.setLayout(null); this.setTitle(null); this.setVisible(true); this.setClosable(false); this.setMaximizable(false); this.setResizable(true); this.addComponentListener(this); this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { vpc.setBounds(vpi.getWidth(),vps.getHeight()+30,vvp.getWidth()-vpi.getWidth()-18,vvp.getHeight()- vps.getHeight()-72); } }); } public void setPanelIzquierdo(PanelIzquierdo pi){ this.vpi=pi; } @Override public void componentHidden(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentMoved(ComponentEvent e) { vps.reshape(vpi.getWidth(), 30,vvp.getWidth()-vpi.getWidth()-18,vvp.getHeight()-vpc.getHeight()-70); } @Override public void componentResized(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } } [/CODE] PANEL IZQUIERDO [CODE]public class PanelIzquierdo extends JInternalFrame implements ComponentListener , MouseListener{ private PanelIzquierdo pi; private VentanaPrincipal vvp; private PanelSuperior vps; private PanelCentral vpc; private JTree tree; public PanelIzquierdo(VentanaPrincipal vp, PanelSuperior vs, PanelCentral vc){ //this.setLayout(null); this.setBounds(0,30,200,768); this.setVisible(true); this.setClosable(false); this.setMaximizable(false); this.setResizable(true); this.setTitle("Navegador"); pi=this; vvp=vp; vps=vs; vpc=vc; this.addComponentListener(this); this.addMouseListener(this); crearJTREE(); this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { vpc.setBounds(pi.getWidth(),260,vvp.getWidth()-pi.getWidth()-18,vvp.getHeight()-302); vps.setBounds(pi.getWidth(),30,vvp.getWidth()-pi.getWidth()-18,vvp.getHeight()-vpc.getHeight()-70); tree.setBounds(0, 0, pi.getWidth(), pi.getHeight()); } }); } @Override public void componentHidden(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentMoved(ComponentEvent e) { pi.reshape(0, 30, 200, vvp.getHeight()-72); } @Override public void componentResized(ComponentEvent e) { // TODO Auto-generated method stub } @Override public void componentShown(ComponentEvent e) { // TODO Auto-generated method stub } public void crearJTREE(){ DefaultMutableTreeNode Sistema = new DefaultMutableTreeNode("Sistema"); DefaultMutableTreeNode hijos = new DefaultMutableTreeNode("hijos"); DefaultTreeModel modelo = new DefaultTreeModel(Sistema); tree = new JTree(modelo); tree.setBounds(0, 0, pi.getWidth(), pi.getHeight()); DefaultMutableTreeNode Medicos = new DefaultMutableTreeNode("Medicos"); DefaultMutableTreeNode Otros = new DefaultMutableTreeNode("Otros"); DefaultMutableTreeNode Altas=new DefaultMutableTreeNode("Altas"); DefaultMutableTreeNode Bajas=new DefaultMutableTreeNode("Bajas"); DefaultMutableTreeNode Quirofano = new DefaultMutableTreeNode("Quirofano"); DefaultMutableTreeNode Otros2=new DefaultMutableTreeNode("Otros 2"); modelo.insertNodeInto(Medicos,Sistema,0); modelo.insertNodeInto(Otros, Sistema, 1); modelo.insertNodeInto(Otros2, Sistema, 2); modelo.insertNodeInto(Altas, Medicos, 0); modelo.insertNodeInto(Bajas, Medicos, 1); modelo.insertNodeInto(Quirofano, Medicos, 2); add(tree); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }[/CODE]

Bueno llamariamos desde main a VentanaPrincipal.

La estructura queda así:




Un saludo.