Centrar pantalla - Resolución de pantalla

Un poco cansado pero sin sueño, quise sentarme a ver este tema que lo tenía en espera para crear la entrada, por lo tanto si escribo dos veces lo mismo espero me comprenda ;).
En esta entrada quise mostrar como podemos centrar una forma según la resolución de la pc.
Para mostrar como hacerlo en el siguiente ejemplo estaremos usando las clases:

-Dimension
- Point
- Toolkit
- JFrame

Ahora procedemos a crear una clase de nombre ResolucionPantalla.

Exported from Notepad++
public class ResolucionPantalla { private int x; private int y; public ResolucionPantalla() { } public Toolkit tomarToolkit() { return Toolkit.getDefaultToolkit(); } public Dimension tomarTamanioPantalla() { return tomarToolkit().getScreenSize(); } public Point centrarPantalla(JFrame frame) { int ancho = (int) getAnchoPantalla(); int altura = (int) getAlturaPantalla(); Dimension dimensionFrame = frame.getSize(); setX((ancho - dimensionFrame.width) / 2); setY((altura - dimensionFrame.height) / 2); frame.setLocation(getX(), getY()); Point p = new Point(); p.setLocation(getX(), getY()); return p; } /** * @return the x */ public int getX() { return x; } /** * @param x the x to set */ public void setX(int x) { this.x = x; } /** * @return the y */ public int getY() { return y; } /** * @param y the y to set */ public void setY(int y) { this.y = y; } /** * @return the alturaPantalla */ public double getAlturaPantalla() { return tomarTamanioPantalla().getHeight(); } /** * @return the anchoPantalla */ public double getAnchoPantalla() { return tomarTamanioPantalla().getWidth(); } @Override public String toString() { StringBuilder builder; builder = new StringBuilder(); int al = (int)getAlturaPantalla(); int an = (int)getAnchoPantalla(); builder.append("x=").append(x).append("\n").append("y=") .append(y).append("\n"); builder.append("altura=").append(al).append("\n"); builder.append("ancho=").append(an); return builder.toString(); } }

Podemos ver la implementación de esta clase en el siguiente ejemplo

Centrar pantalla

Nota: por el momento le dejaré solo el código y otro día iré dando más detalles.
Leer más...

JComboBox codigo y descripción

Cuando trabajamos con combos en aplicaciones donde tenemos tablas de catálogos en base datos relacional necesitamos manejar un código que en la mayoría de las veces es la llave correspondiente al registro.
Para realizar esta funcionalidad estaremos trabajando con las clases:
- ComboBoxModel.
- ListDataEvent.
- ListDataListener.

Bueno para empezar crearemos una clase de nombre Datos, esta clase tendrá 3 atributos que son :
- codigo
- nombre
- edad

Exported from Notepad++
public class Datos<list> { private int codigo; private String nombre; private int edad; /** * @return the codigo */ public int getCodigo() { return codigo; } /** * @param codigo the codigo to set */ public void setCodigo(int codigo) { this.codigo = codigo; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the edad */ public int getEdad() { return edad; } /** * @param edad the edad to set */ public void setEdad(int edad) { this.edad = edad; } @Override public String toString() { return nombre ; } public Datos(int codigo, String nombre, int edad) { this.codigo = codigo; this.nombre = nombre; this.edad = edad; } public Datos() { } }
El siguiente paso será crear la clase ProveedorDatos,

Exported from Notepad++
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import javax.swing.ComboBoxModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; public class ProveedorDatos implements ComboBoxModel { private List<datos> listaDatos = new ArrayList<datos>(); private List<listdatalistener> listaListener = new ArrayList<listdatalistener>(); private Datos datos; public ProveedorDatos() { cargarDatos(); } private void cargarDatos() { for (int i = 1; i &lt;= 10; i++) { datos = new Datos(i, "Nombre " + i, i); listaDatos.add(datos); } } public List tomarDatos() { return listaDatos; } public void setSelectedItem(Object selectedIn) { if (selectedIn instanceof Datos) { datos = (Datos) selectedIn; } else { datos = null; } ListIterator<listdatalistener> ldL = listaListener.listIterator(); while (ldL.hasNext()) { ListDataListener ldl = (ListDataListener) ldL.next(); ldl.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, 0)); } } public Object getSelectedItem() { return datos; } public int getSize() { return listaDatos.size(); } public Object getElementAt(int index) { return listaDatos.get(index); } public void addListDataListener(ListDataListener ldl) { listaListener.add(ldl); } public void removeListDataListener(ListDataListener ldl) { listaListener.remove(ldl); } public String getSelectedDescriscripcion() { if (datos == null) { return null; } else { return datos.getNombre(); } } public int getSelectedCodigo() { if (datos == null) { return -1; } else { return datos.getCodigo(); } } }


Por último usaremos la clase ventana

Exported from Notepad++
import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Ventana extends JFrame implements ActionListener { private JComboBox combo1; private JButton boton1; private String strTitulo; public Ventana(String tituloIn) { strTitulo = tituloIn; } public Ventana() { } public void iniciarComponentes() { ResolucionPantalla res; Container contenedor1; combo1 = new JComboBox(new ProveedorDatos()); boton1 = new JButton("Aceptar"); boton1.setActionCommand("aceptar"); boton1.addActionListener(this); contenedor1 = getContentPane(); contenedor1.setLayout(new FlowLayout()); contenedor1.add(combo1); contenedor1.add(boton1); setVisible(true); setTitle(strTitulo); //le damos un tamaño a la pantalla setSize(300, 100); //centrar pantalla res = new ResolucionPantalla(); setLocation(res.centrarPantalla(this)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent evento) { if (evento.getActionCommand().equals("aceptar")) { ProveedorDatos datosCombo; StringBuilder builder; datosCombo = (ProveedorDatos) combo1.getModel(); builder = new StringBuilder(); builder.append("Código :").append(datosCombo.getSelectedCodigo()). append("\n"); builder.append("Descripción: ").append(datosCombo.getSelectedDescriscripcion()); JOptionPane.showMessageDialog(null, builder.toString(), "Datos Seleccionados", JOptionPane.INFORMATION_MESSAGE); } } public static void main(String arg[]) { Ventana iniciar; iniciar = new Ventana("Obtener código y descripción"); iniciar.iniciarComponentes(); } }

Este es el resultado:








Leer más...