lab sesion7

30
1 LABORATORIO PROGRAMACIÓN JAVA SESIÓN 7: GUIs CON SWING 1. Ejemplos Swing Lo primero que haremos será crear un proyecto llamado SwingGUI donde meteremos todos nuestros ejemplos y ejercicios. 1.1 BOTONES La primera aplicación que haremos consistirá en una ventana con una caja de texto en la que se introducirá un texto que copiaremos en otra caja mediante la pulsación de un botón. Para realizarla tenemos que crear en el proyecto un nuevo fichero de tipo JFrame.

Upload: navaeli

Post on 08-Feb-2016

34 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lab Sesion7

1

LABORATORIO PROGRAMACIÓN JAVA

SESIÓN 7:

GUIs CON SWING

1. Ejemplos Swing

Lo primero que haremos será crear un proyecto llamado SwingGUI donde meteremos todos nuestros

ejemplos y ejercicios.

1.1 BOTONES

La primera aplicación que haremos consistirá en una ventana con una caja de texto en la que se

introducirá un texto que copiaremos en otra caja mediante la pulsación de un botón. Para realizarla

tenemos que crear en el proyecto un nuevo fichero de tipo JFrame.

Page 2: Lab Sesion7

2

Page 3: Lab Sesion7

3

Para realizar la aplicación tendremos que ir arrastrando componentes a la ventana. NetBeans nos

proporciona un Layout propio que irá situando los componentes en el contenedor en las posiciones y

tamaños que nosotros deseemos. Situaremos un JLabel con el texto correspondiente, dos JTextField (en

uno de ellos no se permite la edición) y dos botones.

Para el tratamiento de los eventos, pulsamos con el botón derecho del ratón en cada uno de los botones y

seleccionamos “Events – Action – actionPerformed” y rellenamos con el código en negrita.

En las propiedades del JFrame debemos poner como título de la ventana “BotonesTexto” y desmarcar la

casilla “resizable” y en el código seleccionar “Generate Resize Code”.

Page 4: Lab Sesion7

4

Código final:

package gui;

public class BotonesTexto extends javax.swing.JFrame {

/** Creates new form BotonesTexto */

public BotonesTexto() {

initComponents();

}

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jTextField1 = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jTextField2 = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("BotonesTexto");

setResizable(false);

jLabel1.setText("Introduce un texto y pulsa Copiar");

jButton1.setText("Copiar");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

jButton2.setText("Borrar");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

jTextField2.setEditable(false);

javax.swing.GroupLayout layout

= new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addGroup(layout.createSequentialGroup()

.addGap(39, 39, 39)

.addComponent(jLabel1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addComponent(jButton2)

.addGap(51, 51, 51)))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE,

152, Short.MAX_VALUE)

.addGap(52, 52, 52))

.addGroup(layout.createSequentialGroup()

.addComponent(jTextField2,

javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(61, Short.MAX_VALUE)))

.addGroup(layout.createSequentialGroup()

Page 5: Lab Sesion7

5

.addComponent(jButton1)

.addContainerGap())))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(52, 52, 52)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(31, 31, 31)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jButton2)

.addComponent(jButton1))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21,

Short.MAX_VALUE)

.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(22, 22, 22))

);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-425)/2, (screenSize.height-225)/2, 425, 225);

}// </editor-fold>

//BORRAR

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

jTextField1.setText("");

jTextField2.setText("");

}

//COPIAR

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String txt = jTextField1.getText();

if (txt.equals("")) JOptionPane.showMessageDialog(this,"Rellene el

texto.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

jTextField2.setText(txt);

}

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new BotonesTexto().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JLabel jLabel1;

private javax.swing.JTextField jTextField1;

private javax.swing.JTextField jTextField2;

// End of variables declaration

}

Ejercicio: Escribir un programa que represente una ventana que contenga dos cajas de texto y dos

botones, uno etiquetado con “MAYÚSCULAS” y otro con “minúsculas”. Cuando se pulse el botón de

mayúsculas se deberá convertir el contenido de la primera caja de texto a mayúsculas y si se pulsa el

otro a minúsculas y presentarlo en la segunda caja de texto. Si no hay texto se debe presentar un mensaje

de error.

Page 6: Lab Sesion7

6

1.2 LISTAS

En este ejemplo utilizaremos las listas como componentes principales. Para realizarlo tenemos que crear

en el proyecto un nuevo fichero de tipo JFrame.

En la ventana de aplicación pondremos un JLabel con el texto correspondiente, un JComboBox, un JList

y un JTextField (no se permite la edición).

Para dar los datos iniciales de las listas debemos abrir sus propiedades y editar el campo “Model”.

Para el tratamiento de los eventos, pulsamos con el botón derecho del ratón en cada una de las listas y

seleccionamos: para el JComboBox “Events – Action – actionPerformed” y para el JList “Events –

ListSelection – valueChanged”, por último, rellenamos con el código en negrita.

Código final: package gui;

public class Listas extends javax.swing.JFrame {

Page 7: Lab Sesion7

7

/** Creates new form Listas */

public Listas() {

initComponents();

}

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jComboBox1 = new javax.swing.JComboBox();

jScrollPane1 = new javax.swing.JScrollPane();

jList1 = new javax.swing.JList();

jTextField1 = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("Listas");

setResizable(false);

jLabel1.setText("Selecciona Marca y Equipamiento");

jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Citroen",

"Fiat", "Ford", "Opel", "Peugeot", "Renault" }));

jComboBox1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jComboBox1ActionPerformed(evt);

}

});

jList1.setModel(new javax.swing.AbstractListModel() {

String[] strings = { "ABS", "Aire Ac.", "Air-Bag", "Dir. Asist.", "EE", "Pintura

Met.", "MP3" };

public int getSize() { return strings.length; }

public Object getElementAt(int i) { return strings[i]; }

});

jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

public void valueChanged(javax.swing.event.ListSelectionEvent evt) {

jList1ValueChanged(evt);

}

});

jScrollPane1.setViewportView(jList1);

javax.swing.GroupLayout layout

= new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addGap(41, 41, 41)

.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 155,

Short.MAX_VALUE)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(40, 40, 40))

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 277,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(47, Short.MAX_VALUE))

.addGroup(layout.createSequentialGroup()

.addGap(75, 75, 75)

.addComponent(jLabel1)

.addContainerGap(101, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(27, 27, 27)

.addComponent(jLabel1)

.addGap(8, 8, 8)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

Page 8: Lab Sesion7

8

.addGroup(layout.createSequentialGroup()

.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(39, 39, 39))

.addGroup(layout.createSequentialGroup()

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19,

Short.MAX_VALUE)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(21, 21, 21))

);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-350)/2, (screenSize.height-275)/2, 350, 275);

}// </editor-fold>

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {

// TODO add your handling code here:

//borramos texto e inicializamos equipamiento

jTextField1.setText("");

equipamiento = " - ";

//capturamos los items seleccionados

// y los convertimos en cadena

Object equipo_selec[] = jList1.getSelectedValues();

for(int j=0;j<equipo_selec.length;++j) equipamiento +=

equipo_selec[j]+" - ";

//presentamos la selección de marca y equipamiento

jTextField1.setText(marca_selec+equipamiento);

}

private String marca_selec, equipamiento;

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

//borramos texto

jTextField1.setText("");

//deseleccionamos el equipamiento

jList1.clearSelection();

//capturamos la marca seleccionada

marca_selec = "Marca: "+(String)jComboBox1.getSelectedItem()+" # ";

jTextField1.setText(marca_selec);

}

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Listas().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JComboBox jComboBox1;

private javax.swing.JLabel jLabel1;

private javax.swing.JList jList1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTextField jTextField1;

// End of variables declaration

}

Ejercicio: Escribir un programa que represente una ventana que contenga dos cajas de texto y una lista

desplegable con las opciones “MAYÚSCULAS” y “minúsculas”. Cuando se pulse la opción de

mayúsculas se deberá convertir el contenido de la primera caja de texto a mayúsculas y si se pulsa la otra

a minúsculas y a continuación presentarla en la segunda caja de texto.

Page 9: Lab Sesion7

9

1.3 LISTAS DINÁMICAS

En este ejemplo utilizaremos las listas como componentes principales, pero en este caso las opciones que

aparecen en las listas se recogerán de ficheros de texto para poder hacer cambios de forma dinámica.

Para realizarlo tenemos que crear en el proyecto un nuevo fichero de tipo JFrame.

En la ventana de aplicación pondremos un JLabel con el texto correspondiente, un JComboBox, un JList

y un JTextField (no se permite la edición).

Para dar los datos iniciales de las listas debemos abrir sus propiedades y programar el campo “Model”.

Pulsamos el botón Advanced y rellenamos como se muestra a continuación:

Para el tratamiento de los eventos, pulsamos con el botón derecho del ratón en cada una de las listas y

seleccionamos: para el JComboBox “Events – Action – actionPerformed” y para el JList “Events –

ListSelection – valueChanged”, por último, rellenamos con el código en negrita.

Page 10: Lab Sesion7

10

Código final: package gui;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.Vector;

import javax.swing.JComboBox;

public class ListasDin extends javax.swing.JFrame {

/** Creates new form ListasDin */

public ListasDin() {

initComponents();

jComboBox1.setSelectedIndex(0);

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jComboBox1 = new javax.swing.JComboBox();

jTextField1 = new javax.swing.JTextField();

jScrollPane1 = new javax.swing.JScrollPane();

jList1 = new javax.swing.JList();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setResizable(false);

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));

jLabel1.setText("Selecciona una marca de portatil y extras:");

getMarcas();

jComboBox1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jComboBox1ActionPerformed(evt);

}

});

jTextField1.setEditable(false);

getExtras();

jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

public void valueChanged(javax.swing.event.ListSelectionEvent evt) {

jList1ValueChanged(evt);

}

});

jScrollPane1.setViewportView(jList1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(36, 36, 36)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jLabel1)

.addGroup(layout.createSequentialGroup()

.addGap(22, 22, 22)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE,

307, Short.MAX_VALUE)

.addGroup(layout.createSequentialGroup()

Page 11: Lab Sesion7

11

.addComponent(jComboBox1,

javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(41, 41, 41)

.addComponent(jScrollPane1,

javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)))))

.addGap(36, 36, 36))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(59, 59, 59)

.addComponent(jLabel1)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(45, 45, 45)

.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addGap(22, 22, 22)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,

91, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addGap(30, 30, 30)

.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(56, Short.MAX_VALUE))

);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-416)/2, (screenSize.height-336)/2, 416, 336);

}// </editor-fold>

private String marca_selec, extras;

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {

// TODO add your handling code here:

//borramos texto e inicializamos equipamiento

jTextField1.setText("");

extras = " - ";

//capturamos los items seleccionados

// y los convertimos en cadena

Object extras_selec[] = jList1.getSelectedValues();

for(int j=0;j<extras_selec.length;++j) extras += extras_selec[j]+" - ";

//presentamos la selección de marca y equipamiento

jTextField1.setText(marca_selec+extras);

}

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

//borramos texto

jTextField1.setText("");

//deseleccionamos el equipamiento

jList1.clearSelection();

//capturamos la marca seleccionada

marca_selec = "Marca: "+(String)jComboBox1.getSelectedItem()+" # ";

jTextField1.setText(marca_selec);

}

// rellenamos las opciones de la lista desplegable

private void getMarcas() {

String cad;

Vector marcas = new Vector();

try {

BufferedReader br =

new BufferedReader(new FileReader("marcas.txt"));

while ((cad = br.readLine()) != null) {

marcas.add(cad);

}

//Cerramos el stream

br.close();

jComboBox1 = new JComboBox(marcas);

} catch (IOException ioe) {

Page 12: Lab Sesion7

12

System.out.println(ioe);

}

}

// rellenamos las opciones de la lista

private void getExtras() {

String cad;

Vector extras = new Vector();

try {

BufferedReader br =

new BufferedReader(new FileReader("extras.txt"));

while ((cad = br.readLine()) != null) {

extras.add(cad);

}

//Cerramos el stream

br.close();

jList1.setListData(extras);

} catch (IOException ioe) {

System.out.println(ioe);

}

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new ListasDin().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JComboBox jComboBox1;

private javax.swing.JLabel jLabel1;

private javax.swing.JList jList1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTextField jTextField1;

// End of variables declaration

}

Page 13: Lab Sesion7

13

2. Ejercicio Calculadora Swing

Escribir un programa en Java que permita realizar las operaciones típicas de una calculadora: suma,

resta, multiplicación y división. El usuario introducirá el operando 1 el 2 y luego seleccionará la

operación a realizar, mostrando el resultado correspondiente. También debe tener la posibilidad de

convertir de pesetas a euros y viceversa. El programa deberá tratar todos los posibles errores en tiempo

de ejecución, dando un mensaje con un diálogo de error.

El aspecto gráfico del programa puede ser como el siguiente:

3. Ejercicio Censo

El segundo ejercicio consiste en la gestión de un censo donde tenemos los datos de una serie de

personas. Las operaciones que se pueden hacer en la aplicación serán las típicas de este tipo de SI, es

decir, altas, bajas, modificaciones y consultas. Utilizaremos una clase Persona que nos servirá como base

de la aplicación y que tendrá como atributos el DNI, el nombre, la dirección y el teléfono.

A continuación se presentan unas pantallas de la aplicación a modo de ejemplo.

Page 14: Lab Sesion7

14

4. Solución Aplicación Censo Swing

4.1 Proyecto Censo

Lo primero que debemos hacer es crear un proyecto de tipo Java Application llamado Censo.

4.2 Clases Persona y UtilCenso

Una vez creado el proyecto vamos a crear la clase Persona que será la encargada de almacenar los datos

de la aplicación.

Debemos crear todos los atributos y los métodos que necesitemos de forma que el código final quedará

así:

package censo;

import java.io.Serializable;

public class Persona implements Serializable {

/** Creates a new instance of Persona */

public Persona(String p_dni, String p_nombre, String p_direccion, int p_tfno) {

dni = p_dni;

nombre = p_nombre;

direccion = p_direccion;

tfno = p_tfno;

}

private String dni;

private String nombre;

private String direccion;

private int tfno;

public String getDni() {

return this.dni;

}

public String getNombre() {

return this.nombre;

}

public void setNombre(String nombre) {

this.nombre = nombre;

}

public String getDireccion() {

return this.direccion;

}

public void setDireccion(String direccion) {

this.direccion = direccion;

}

public int getTfno() {

return this.tfno;

}

public void setTfno(int tfno) {

Page 15: Lab Sesion7

15

this.tfno = tfno;

}

public String toString() {

return dni + " " + nombre;

}

}

Como tenemos que realizar una serie de operaciones con los objetos de tipo persona vamos a crear una

clase de utilidades que permita la gestión de los mismos.

package censo;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.*;

public class UtilCenso {

/** Creates a new instance of UtilCenso */

public UtilCenso() {

}

private static HashMap<String, Persona> personas = new HashMap<String,

Persona>();

public static boolean vacia() {

return personas.isEmpty();

}

public static void setPersonas(HashMap p) {

personas = p;

}

public static HashMap getPersonas() {

return personas;

}

/* Devolvemos un array con las personas ordenadas por nombre */

public static Object[] getArrayPersonas() {

//Comparador para ordenar las personas por su nombre

Comparator NomPerComp = new Comparator() {

public int compare(Object o1, Object o2) {

Persona p1 = (Persona) o1;

Persona p2 = (Persona) o2;

return p1.getNombre().compareTo(p2.getNombre());

}

};

//array auxiliar

Object peraux[];

//Cargamos todas las personas en un array

peraux = personas.values().toArray();

//Ordenamos el array

Arrays.sort(peraux, NomPerComp);

return peraux;

}

public static void altaPersona(Persona objper) {

personas.put(objper.getDni(), objper);

}

public static void bajaPersona(String dni) {

Page 16: Lab Sesion7

16

personas.remove(dni);

}

public static boolean modificaPersona(String p_dni, String p_nombre,

String p_direccion, int p_tfno) {

Persona p = personas.get(p_dni);

if (p == null) {

return false;

}

p.setNombre(p_nombre);

p.setDireccion(p_direccion);

p.setTfno(p_tfno);

return true;

}

public static Persona consultaPersona(String dni) {

Persona objper = (Persona) personas.get(dni);

return objper;

}

/* Carga los datos de personas del fichero */

public static void cargarDatos() {

try {

//Lectura de los objetos de tipo persona

FileInputStream istreamPer = new FileInputStream("copiasegPer.dat");

ObjectInputStream oisPer = new ObjectInputStream(istreamPer);

personas = (HashMap) oisPer.readObject();

istreamPer.close();

} catch (IOException ioe) {

System.out.println("Error de IO: " + ioe.getMessage());

} catch (ClassNotFoundException cnfe) {

System.out.println("Error de clase no encontrada: "

+ cnfe.getMessage());

} catch (Exception e) {

System.out.println("Error: " + e.getMessage());

}

}//fin cargarDatos

/* Guarda los datos de personas en el fichero */

public static void guardarDatos() {

try {

//Si hay datos los guardamos...

if (!vacia()) {

/****** Serialización de los objetos ******/

//Serialización de las personas

FileOutputStream ostreamPer =

new FileOutputStream("copiasegPer.dat");

ObjectOutputStream oosPer = new ObjectOutputStream(ostreamPer);

//guardamos la hashtable de personas

oosPer.writeObject(personas);

ostreamPer.close();

} else {

System.out.println("Error: No hay datos...");

}

} catch (IOException ioe) {

System.out.println("Error de IO: " + ioe.getMessage());

} catch (Exception e) {

System.out.println("Error: " + e.getMessage());

}

}//fin guardarDatos

}

Page 17: Lab Sesion7

17

4.3 Frame Censo

Con respecto a la interfaz lo primero que debemos hacer es crear un frame que represente la ventana

principal.

Código final:

package censo;

public class Censo extends javax.swing.JFrame {

/** Creates new form Censo */

public Censo() {

UtilCenso.cargarDatos();

initComponents();

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jLabel2 = new javax.swing.JLabel();

Page 18: Lab Sesion7

18

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("CENSO");

setResizable(false);

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent evt) {

formWindowClosing(evt);

}

});

getContentPane().setLayout(null);

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N

jLabel1.setText("CENSO");

jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

getContentPane().add(jLabel1);

jLabel1.setBounds(160, 20, 80, 29);

jButton1.setText("ALTAS");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

getContentPane().add(jButton1);

jButton1.setBounds(120, 120, 160, 23);

jButton2.setText("CONSULTAS");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

getContentPane().add(jButton2);

jButton2.setBounds(120, 180, 160, 23);

jLabel2.setFont(new java.awt.Font("Tahoma", 2, 18)); // NOI18N

jLabel2.setText("SELECCIONA OPCIÓN");

jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

getContentPane().add(jLabel2);

jLabel2.setBounds(110, 70, 180, 22);

java.awt.Dimension screenSize

= java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-396)/2, (screenSize.height-318)/2, 396, 318);

}// </editor-fold>

Page 19: Lab Sesion7

19

//CONSULTAS

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Consultas c = new Consultas(this);

}

//ALTAS

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

Altas a = new Altas(this);

}

private void formWindowClosing(java.awt.event.WindowEvent evt) {

// TODO add your handling code here:

UtilCenso.guardarDatos();

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Censo().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

// End of variables declaration

}

Page 20: Lab Sesion7

20

4.4 Panel Datos

Una vez creada la ventana principal vamos a pasar a realizar las ventanas de altas y consultas.

Como ambos frames comparten el mismo formulario de datos de las personas, crearemos un “JPanel”

que contenga esos datos.

Para poder acceder a los campos de texto desde cualquier frame necesitamos una serie de métodos que

nos permitan tanto escribir como leer de ellos. El código final sería el siguiente:

Código final:

package censo;

public class PanelDatos extends javax.swing.JPanel {

/** Creates new form PanelDatos */

public PanelDatos() {

initComponents();

}

//metodos para devolver y presentar el contenido de las cajas de texto

public String getJTextFieldDir() {

return jTextFieldDir.getText();

}

public void setJTextFieldDir(String txt) {

this.jTextFieldDir.setText(txt);

}

public String getJTextFieldDni() {

Page 21: Lab Sesion7

21

return jTextFieldDni.getText();

}

public void setJTextFieldDni(String txt) {

this.jTextFieldDni.setText(txt);

}

public String getJTextFieldNom() {

return jTextFieldNom.getText();

}

public void setJTextFieldNom(String txt) {

this.jTextFieldNom.setText(txt);

}

public String getJTextFieldTfno() {

return jTextFieldTfno.getText();

}

public void setJTextFieldTfno(String txt) {

this.jTextFieldTfno.setText(txt);

}

//borra el contenido del panel

public void borrar() {

setJTextFieldDni("");

setJTextFieldNom("");

setJTextFieldDir("");

setJTextFieldTfno("");

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

jTextFieldDni = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();

jTextFieldNom = new javax.swing.JTextField();

jLabel3 = new javax.swing.JLabel();

jTextFieldDir = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

jTextFieldTfno = new javax.swing.JTextField();

setBackground(new java.awt.Color(153, 255, 153));

setLayout(new java.awt.GridLayout(4, 2));

jLabel1.setText("DNI");

add(jLabel1);

add(jTextFieldDni);

jLabel2.setText("NOMBRE");

add(jLabel2);

add(jTextFieldNom);

jLabel3.setText("DIRECCIÓN");

add(jLabel3);

add(jTextFieldDir);

jLabel4.setText("TFNO");

Page 22: Lab Sesion7

22

add(jLabel4);

add(jTextFieldTfno);

}// </editor-fold>

// Variables declaration - do not modify

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JTextField jTextFieldDir;

private javax.swing.JTextField jTextFieldDni;

private javax.swing.JTextField jTextFieldNom;

private javax.swing.JTextField jTextFieldTfno;

// End of variables declaration

}

Para que esté disponible para los frames de altas y consulta debemos añadirlo a la paleta de

componentes, pulsando con el botón derecho en PanelDatos.java – Tools – Add to Pallete.

4.5 Frame Altas

Ahora pasamos a realizar el frame de Altas. Utilizaremos un layout nulo donde pondremos nuestros

componentes. Este frame se encargará de ocultar la ventana principal para que el usuario no pueda

realizar más acciones con ella y solo trabaje con una ventana a la vez.

Page 23: Lab Sesion7

23

Código final:

package censo;

import javax.swing.*;

public class Altas extends javax.swing.JFrame {

private JFrame principal;

/** Creates new form Altas */

public Altas(JFrame ventana) {

initComponents();

principal = ventana;

principal.setVisible(false);

this.setVisible(true);

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

panelDatos1 = new censo.PanelDatos();

jButton1 = new javax.swing.JButton();

jButton2 = new javax.swing.JButton();

jLabel1 = new javax.swing.JLabel();

getContentPane().setLayout(null);

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

setTitle("ALTAS");

setResizable(false);

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosed(java.awt.event.WindowEvent evt) {

formWindowClosed(evt);

}

});

getContentPane().add(panelDatos1);

panelDatos1.setBounds(14, 106, 370, 160);

jButton1.setText("ALTA");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

getContentPane().add(jButton1);

jButton1.setBounds(70, 50, 70, 23);

jButton2.setText("BORRAR");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

getContentPane().add(jButton2);

jButton2.setBounds(250, 50, 80, 23);

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));

Page 24: Lab Sesion7

24

jLabel1.setText("ALTAS CENSO");

getContentPane().add(jLabel1);

jLabel1.setBounds(140, 10, 120, 22);

java.awt.Dimension screenSize =

java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-400)/2, (screenSize.height-325)/2, 400, 325);

}

// </editor-fold>

//Cerrar ventana

private void formWindowClosed(java.awt.event.WindowEvent evt) {

// TODO add your handling code here:

//Volvemos a mostrar la ventana principal

principal.setVisible(true);

}

//BORRAR

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

panelDatos1.borrar();

}

//ALTA

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String dni = panelDatos1.getJTextFieldDni();

String nombre = panelDatos1.getJTextFieldNom();

String dir = panelDatos1.getJTextFieldDir();

int tfno = Integer.parseInt(panelDatos1.getJTextFieldTfno());

Persona objper= new Persona(dni, nombre, dir, tfno);

UtilCenso.altaPersona(objper);

JOptionPane.showMessageDialog(this,"Persona dada de

alta.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JLabel jLabel1;

private censo.PanelDatos panelDatos1;

// End of variables declaration

}

Page 25: Lab Sesion7

25

4.6 Frame Consultas

Ahora pasamos a realizar el frame de Consultas. Utilizaremos un layout nulo donde pondremos nuestros

componentes. Este frame se encargará de ocultar la ventana principal para que el usuario no pueda

realizar más acciones con ella y solo trabaje con una ventana a la vez.

Código final:

package censo;

import javax.swing.*;

public class Consultas extends javax.swing.JFrame {

private JFrame principal;

/** Creates new form Consultas */

public Consultas(JFrame ventana) {

initComponents();

consultarTodo();

principal = ventana;

principal.setVisible(false);

this.setVisible(true);

}

Persona objper;

private Object peraux[];

private int contador=0;

/** Consulta las personas de la tabla hash y las ordena para su presentación */

private void consultarTodo() {

try {

Page 26: Lab Sesion7

26

contador=0;

//Cargamos todas las personas en un array

peraux = UtilCenso.getArrayPersonas();

//Si no hay personas...

if (peraux.length<1) {

JOptionPane.showMessageDialog(this,"No hay

personas.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

jButton3.setEnabled(false);

jButton4.setEnabled(false);

return;

} else {

jButton3.setEnabled(true);

jButton4.setEnabled(true);

}

//Presentamos la primera persona

objper = (Persona) peraux[0];

if (objper != null) {

presenta(objper);

} else {

JOptionPane.showMessageDialog(this,"No hay

personas.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

return;

}

} catch (Exception e) {

JOptionPane.showMessageDialog(this,"Error:

"+e.getMessage(),"Mensaje",JOptionPane.ERROR_MESSAGE);

System.out.println("Error: "+e.toString());

return;

}

}//fin consultarTodo

/** Presenta los datos de una persona */

private void presenta(Persona objper) {

panelDatos1.setJTextFieldDni(objper.getDni());

panelDatos1.setJTextFieldNom(objper.getNombre());

panelDatos1.setJTextFieldDir(objper.getDireccion());

panelDatos1.setJTextFieldTfno(""+objper.getTfno());

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

// <editor-fold defaultstate="collapsed" desc=" Generated Code ">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

panelDatos1 = new censo.PanelDatos();

jButton2 = new javax.swing.JButton();

jButton1 = new javax.swing.JButton();

jButton3 = new javax.swing.JButton();

jButton4 = new javax.swing.JButton();

jButton5 = new javax.swing.JButton();

jButton6 = new javax.swing.JButton();

getContentPane().setLayout(null);

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

setTitle("CONSULTAS");

setResizable(false);

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosed(java.awt.event.WindowEvent evt) {

formWindowClosed(evt);

}

Page 27: Lab Sesion7

27

});

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));

jLabel1.setText("CONSULTAS CENSO");

getContentPane().add(jLabel1);

jLabel1.setBounds(110, 10, 170, 22);

getContentPane().add(panelDatos1);

panelDatos1.setBounds(14, 116, 370, 140);

jButton2.setFont(new java.awt.Font("Tahoma", 2, 11));

jButton2.setText("BORRAR");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

getContentPane().add(jButton2);

jButton2.setBounds(300, 260, 80, 23);

jButton1.setText("CONSULTAR");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

getContentPane().add(jButton1);

jButton1.setBounds(20, 50, 120, 23);

jButton3.setFont(new java.awt.Font("Tahoma", 1, 12));

jButton3.setText("SIG");

jButton3.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton3ActionPerformed(evt);

}

});

getContentPane().add(jButton3);

jButton3.setBounds(110, 90, 60, 23);

jButton4.setFont(new java.awt.Font("Tahoma", 1, 12));

jButton4.setText("ANT");

jButton4.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton4ActionPerformed(evt);

}

});

getContentPane().add(jButton4);

jButton4.setBounds(220, 90, 70, 23);

jButton5.setText("MODIFICAR");

jButton5.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton5ActionPerformed(evt);

}

});

getContentPane().add(jButton5);

jButton5.setBounds(160, 50, 110, 23);

jButton6.setText("BAJA");

Page 28: Lab Sesion7

28

jButton6.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton6ActionPerformed(evt);

}

});

getContentPane().add(jButton6);

jButton6.setBounds(290, 50, 80, 23);

java.awt.Dimension screenSize =

java.awt.Toolkit.getDefaultToolkit().getScreenSize();

setBounds((screenSize.width-400)/2, (screenSize.height-325)/2, 400, 325);

}

// </editor-fold>

//Cerrar ventana

private void formWindowClosed(java.awt.event.WindowEvent evt) {

// TODO add your handling code here:

//Volvemos a mostrar la ventana principal

principal.setVisible(true);

}

//BORRAR

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

panelDatos1.borrar();

}

//ANT

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

//Comprobamos el rango del array...

if (contador>=1 && contador<=peraux.length-1) {

contador--;

objper = (Persona) peraux[contador];

if (objper != null) {

presenta(objper);

} else {

JOptionPane.showMessageDialog(this,"No hay

personas.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

}

}

return;

}

//SIG

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

//Comprobamos el rango del array...

if (contador>=0 && contador<=peraux.length-2) {

contador++;

objper = (Persona) peraux[contador];

if (objper != null) {

presenta(objper);

} else {

JOptionPane.showMessageDialog(this,"No hay

personas.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

}

}

return;

}

//BAJA

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {

Page 29: Lab Sesion7

29

// TODO add your handling code here:

String dni = panelDatos1.getJTextFieldDni();

//obtenemos la persona de la tabla hash.

objper = UtilCenso.consultaPersona(dni);

if (objper != null) {

UtilCenso.bajaPersona(dni);

JOptionPane.showMessageDialog(this,"Persona dada de baja: "+

objper.toString(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);

panelDatos1.borrar();

} else {

JOptionPane.showMessageDialog(this," Error: - Persona no encontrada –

","Mensaje",JOptionPane.ERROR_MESSAGE);

}

consultarTodo();

return;

}

//MODIFICAR

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String dni = panelDatos1.getJTextFieldDni();

//obtenemos la persona de la tabla hash.

objper = UtilCenso.consultaPersona(dni);

if (objper != null) {

//capturamos la nueva información y modificamos el objeto

String nombre = panelDatos1.getJTextFieldNom();

String dir = panelDatos1.getJTextFieldDir();

int tfno = Integer.parseInt(panelDatos1.getJTextFieldTfno());

UtilCenso.modificaPersona(dni, nombre, dir, tfno);

JOptionPane.showMessageDialog(this,"Persona modificada: "+

objper.toString(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);

panelDatos1.borrar();

consultarTodo();

} else {

JOptionPane.showMessageDialog(this," Error: - Persona no encontrada –

","Mensaje",JOptionPane.ERROR_MESSAGE);

}

return;

}

//CONSULTAR

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String dni = panelDatos1.getJTextFieldDni();

if ( dni.equals("") ) {

JOptionPane.showMessageDialog(this,"Rellene el DNI de la

persona.","Mensaje",JOptionPane.INFORMATION_MESSAGE);

return;

}

//obtenemos la persona de la tabla hash.

objper = UtilCenso.consultaPersona(dni);

if (objper != null) {

//presentamos la información

presenta(objper);

//Calculamos la posición de la persona en el array

for (int j=0; j<=peraux.length; j++) {

if ( objper.equals((Persona) peraux[j]) ) {

contador=j;

break;

}

}

} else {

Page 30: Lab Sesion7

30

JOptionPane.showMessageDialog(this," Error: - Persona no encontrada –

","Mensaje",JOptionPane.ERROR_MESSAGE);

consultarTodo();

}

return;

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JButton jButton2;

private javax.swing.JButton jButton3;

private javax.swing.JButton jButton4;

private javax.swing.JButton jButton5;

private javax.swing.JButton jButton6;

private javax.swing.JLabel jLabel1;

private censo.PanelDatos panelDatos1;

// End of variables declaration

}