Usuario:ManuelRomero/CursoJavaUml/Practicas/practica 5

De WikiEducator
< Usuario:ManuelRomero‎ | CursoJavaUml
Revisión a fecha de 22:17 9 may 2012; ManuelRomero (Discusión | contribuciones)

(dif) ← Revisión anterior | Revisión actual (dif) | Revisión siguiente → (dif)
Saltar a: navegación, buscar

ICliente

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
 
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.Event.*;
import java.sql.*;
 
 
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ICliente extends JFrame{
 
 
	//	Definición de objetos gráficos para el interfaz
	JLabel lNum = new JLabel ("Número");
	JTextField  tNum = new JTextField(5);
	JLabel lApellido = new JLabel("Apellido");
	JTextField tApellido = new JTextField (5);
	JLabel lNombre = new JLabel("Nombre");
	JTextField tNombre = new JTextField (5);
	private JMenuItem mIDesconectar;
	private JMenuItem mIConectar;
	private JMenu jMenu1;
	private JMenuBar barraMenu;
	private JLabel jLabel3;
	private JFormattedTextField tDNI;
	private JLabel jLabel2;
	private JTextField tDireccion;
	private JLabel jLabel1;
	JButton bPrimero = new JButton("primero");
	JButton bAnterior = new JButton("anterior");
	JButton bSiguiente= new JButton("siguiente");
 
	JButton bUltimo = new JButton("ultimo");
//Paneles contenedores además del contenedor principal que es el frame
	JPanel pDatos = new JPanel();
	JPanel pBotones = new JPanel();
//Layout para distribución de objetos en el contenedor	
	//FlowLayout fL = new FlowLayout();
	BoxLayout bL = new BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS);
	BoxLayout bxL = new BoxLayout(this.getContentPane(),BoxLayout.LINE_AXIS);
 
//para poderme comunciar con otras clases	
	Cliente cliente = new Cliente();
    ResultSet clientes; //Para trabajar con el resultado de una consulta concreta
    ResultSet cuentas; //Para trabajar con el resultado de una consulta concreta
	Conexion conexion; //static para poder ser usada en el main que es static
 
	//Objetos para el jTable y DefaultTableModel
	private DefaultTableModel modelo = new DefaultTableModel();
	private JTable taCuentas = new JTable(modelo);
	private JPanel pCuentas;
	JScrollPane scroll;
 
 
 
 
 public ICliente(){
	//Ponemos los layout
 
	// pBotones.setLayout(fL);
     getContentPane().setLayout(bL);
     getContentPane().add(getJLabel3());
     GridBagLayout pDatosLayout = new GridBagLayout();
     pDatos.setLayout(pDatosLayout);
     getContentPane().add(pDatos);
 
 
    //Añadimos los objetos a los contenedores
     //primero los contenidos a los paneles
     pBotones.add(bPrimero);
     pBotones.add(bSiguiente);
     pBotones.add(bAnterior);
     pBotones.add(bUltimo);
 
     pDatos.add(lNum, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
     lNum.setText("Número de cliente");
     pDatos.add(tNum, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
     pDatos.add(lNombre, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 0), 0, 0));
     pDatos.add(tNombre, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
     pDatos.add(lApellido, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
     pDatos.add(tApellido, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
     {
    	 jLabel1 = new JLabel();
    	 pDatos.add(jLabel1, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    	 jLabel1.setText("Dirección");
     }
     {
    	 tDireccion = new JTextField();
    	 pDatos.add(tDireccion, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    	 tDireccion.setColumns(10);
     }
     {
    	 jLabel2 = new JLabel();
    	 pDatos.add(jLabel2, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    	 jLabel2.setText("DNI");
     }
     {
 
    	 tDNI = new JFormattedTextField();
    	 pDatos.add(tDNI, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    	 tDNI.setColumns(10);
     }
 
 
 	pCuentas = new JPanel();
 	pCuentas.setBorder(BorderFactory.createTitledBorder("Cuentas Bancarias de cliente"));
 	pCuentas.add(getTaCuentas());
    getContentPane().add(pCuentas);
    pCuentas.setSize(584, 200);
    pCuentas.setPreferredSize(new java.awt.Dimension(584, 500));
 
     //Luego los paneles al JFrame
     getContentPane().add(pBotones);
     pBotones.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, new java.awt.Color(255,128,64), new java.awt.Color(255,128,64), new java.awt.Color(255,128,64), new java.awt.Color(255,128,64)));
     pBotones.setPreferredSize(new java.awt.Dimension(584, 39));
     pDatos.setBorder(BorderFactory.createTitledBorder(null, "Datos Cliente", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI",3,14), new java.awt.Color(0,0,255)));
     pDatos.setPreferredSize(new java.awt.Dimension(912, 147));
     pDatosLayout.rowWeights = new double[] {0.1, 0.1, 0.1, 0.1};
     pDatosLayout.rowHeights = new int[] {7, 7, 7, 7};
     pDatosLayout.columnWeights = new double[] {0.1, 0.1, 0.1, 0.1};
     pDatosLayout.columnWidths = new int[] {7, 7, 7, 7};
 
 
 
     //Colocamos y visualizamos el JFrame
     this.setBounds(0, 0, 600, 335);
     setTitle("Recorrido de la tabla Clientes");
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setVisible(true);
     {
    	 barraMenu = new JMenuBar();
    	 setJMenuBar(barraMenu);
    	 barraMenu.add(getJMenu1());
     }
 
     //Cremos un objeto escuchador de la interfaz ActionListener
 
 
     //Agregamos este objeto a los botones desde los que quieremos recoger el evento
 
 
     //Realizamos la consulta para después moverme sobre ella (avanzar o retroceder).
 
 
 }
 public void cargaDatos(Cliente c){
	 tNombre.setText(c.getNombre());
	 tApellido.setText(c.getApellido());
	 tNum.setText(c.getNumero().toString());
 
 }
 public static void main(String []s){
       ICliente ventanaCliente = new ICliente();
 }
 
 private JScrollPane getTaCuentas() {
 
 
	 modelo = new DefaultTableModel();
	 taCuentas = new JTable(modelo);
	 //taCuentas.setPreferredScrollableViewportSize(new Dimension(500,50));
	 scroll = new JScrollPane(taCuentas);
	return scroll;
	}
 
 private JLabel getJLabel3() {
		if(jLabel3 == null) {
			jLabel3 = new JLabel();
			jLabel3.setText("Clientes y sus cuentas bancarias");
			jLabel3.setFont(new java.awt.Font("Segoe UI",3,26));
			jLabel3.setForeground(new java.awt.Color(128,128,192));
			jLabel3.setPreferredSize(new java.awt.Dimension(571, 36));
			jLabel3.setAlignmentY(0.0f);
		}
		return jLabel3;
	}
 private JMenu getJMenu1() {
		if(jMenu1 == null) {
			jMenu1 = new JMenu();
			jMenu1.setText("Base de datos");
			jMenu1.add(getMIConectar());
			jMenu1.add(getMIDesconectar());
		}
		return jMenu1;
	}
 private JMenuItem getMIConectar() {
		if(mIConectar == null) {
			mIConectar = new JMenuItem();
			mIConectar.setText("Conectar");
			mIConectar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					clickConectar();
					//TODO add your code for mIConectar.actionPerformed
				}
			});
		}
		return mIConectar;
	}
 private JMenuItem getMIDesconectar() {
		if(mIDesconectar == null) {
			mIDesconectar = new JMenuItem();
			mIDesconectar.setText("Desconectar");
		}
		return mIDesconectar;
	}
/**
 * Escribo el código asociado a los eventos
 */
 private void clickConectar(){
	 try{
	 System.out.println("Intentando conectar");
		if (conexion==null){
			conexion = new Conexion();
			clientes = conexion.hacerConsulta("Select * from clientes");
			  System.out.println("Creada consulta y consultado clientes");
 
			if (clientes.next()){
				 cliente.setDatosCliente(clientes);
				 cargarPrimerCliente();
			}
			else{
				System.out.println("Actualmente no hay clientes");
			}
		}
		else
			JOptionPane.showMessageDialog(this,"Actualmente conectado a la BD");
		}
		catch(SQLException e){
			  System.out.println("Error haciendo la conexión en interfaz");
		}
 }
 private void cargarPrimerCliente(){
	 try{
/*	 if (clientes.isFirst())
		 JOptionPane.showMessageDialog(this,"Este es el primer registro");
	 else
	 */
		 if (clientes.first()){
		    cargarCliente();	 
 
	     }
	 }catch(SQLException e){
		 System.out.println("Visualizando el primero cliente");
	 }
 }
 
 private void cargarCliente(){
 
	 tNum.setText(""+cliente.getNumero());
	 tNombre.setText(cliente.getNombre());
	 tApellido.setText(cliente.getApellido());
	 tDireccion.setText(cliente.getDireccion());
	 tDNI.setText(cliente.getDni());
	 rellenaCuentasSocio(cliente.getNumero());
 
 }
 
 private void rellenaCuentasSocio(int numSocio){
	 //Obetener información de un meta
try{	 
	ResultSet ccc;
	  System.out.println("Consultando del cliente "+numSocio);
	 ccc=conexion.hacerConsulta("Select * from cuentabancaria where cliente ="+numSocio);
	 System.out.println("chivato 1");
	   ResultSetMetaData rsmd = ccc.getMetaData();
	   System.out.println("chivato 2 "+rsmd.getColumnName(1));
	   int columnas= rsmd.getColumnCount();
	   System.out.println("Se han encontrado "+columnas +"columnas");
	   /*
	   Object[] etiquetas = new Object[columnas];
       for (int i = 0; i < columnas; i++)
       {
           etiquetas[i] = rsmd.getColumnLabel(i + 1);
       }
 
       // Se meten las etiquetas en el modelo. El numero
       // de columnas se ajusta automáticamente.
       modelo.setColumnIdentifiers(etiquetas);
       */
	   for (int i=0;i<columnas;i++){
		   modelo.addColumn(rsmd.getColumnName(i+1));
		   System.out.println("chivato 2 "+rsmd.getColumnName(i+1));
	   }
 
 
 
	   while (ccc.next()){
		   // Se crea un array que será una de las filas de la tabla.
		   Object [] fila = new Object[columnas]; // Hay tres columnas en la tabla
 
		   // Se rellena cada posición del array con una de las columnas de la tabla en base de datos.
		   for (int i=0;i<columnas;i++)
		      fila[i] = ccc.getObject(i+1); // El primer indice en rs es el 1, no el cero, por eso se suma 1.
 
		   // Se añade al modelo la fila completa.
		   modelo.addRow(fila);
		   //modelo.setValueAt("",0,0);
	   }
 
	 }catch(SQLException e){
		   System.out.println("Error en la tablita Se han encontrado "+e.getMessage());
 
	 }
 
 
 }
}//End class

Cliente

Cliente {
	int numero;
	String nombre;
	String apellido;
	String dni;
	String direccion;
 
 
	public Cliente(){
 
	}
 
	public void setDatosCliente( ResultSet c){
		try{	
			setNumero(c.getInt("numsocio"));
			setNombre(c.getString("nombre"));
			setApellido(c.getString("apellidos"));
			setDireccion(c.getString("direccion"));
			setDni(c.getString("dni"));
		}catch(SQLException ex){
			JOptionPane.showMessageDialog(null, "Error recuperando datos de un resultset \n"+ex.getMessage());
		}
	}//Fin de setDatos
 
	public String getNombre(){
		return nombre;
	}
 
	public String getDireccion(){
		return direccion;
	}
	public String getDni(){
		return dni;
	}
	public void setDireccion(String direccion){
		this.direccion=direccion;
	}
	public void setDni(String dni){
		this.dni=dni;
	}
 
	public String getApellido(){
		return apellido;
	}
 
	public Integer getNumero(){
		return numero;
	}
 
	public void setNumero(int numero){
		this.numero=numero;
	}
 
	public void setNombre(String nombre){
		this.nombre=nombre;
	}
 
	public void setApellido(String apellido){
		this.apellido=apellido;
	}
 
}

Coenxion

import java.sql.*;
 
 
import javax.swing.JOptionPane;
public class Conexion {
final String DRIVER = "com.mysql.jdbc.Driver";  	
final String BD = "jdbc:mysql://localhost/concesionario";
Connection con;
Statement instruccion;
ResultSet resultado;
 
 
public Conexion(){
	try{
		Class.forName(DRIVER);
		con = DriverManager.getConnection(BD,"manolo","");
		instruccion = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		System.out.println("Conectadoooooooo");
	}catch (ClassNotFoundException e){
		System.out.println("Conexion() Clase no encontrada");
 
	}catch (SQLException e){
		System.out.println("Conexion() Excepción sql"+e.getMessage());
	}
}
public ResultSet hacerConsulta(String  consulta){
	try{
	 return instruccion.executeQuery(consulta);
	}
	 catch(SQLException e){
		  System.out.println("Error haciendo consulta en conexión");
		 return null;
	 }
 
}
 
public Connection getConexion(){
	return con;
}
 
 
public Statement getInstruccion(){
	return instruccion;
}
 
public void CerrarBD(){
	try{
	 instruccion.close();
	 con.close();
	}catch(SQLException e){
	  JOptionPane.showMessageDialog(null,"Error cerrando la bd"+ e.getMessage());
	}
 
}
 
}//End la clase conexion