lunes, 18 de agosto de 2014

Datos de entrada en JFormattedTextField


algo un poco mas complicado a ver si entienden jaja es mas complicado y  mejor que el JTextField



import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;

/**
 * Además de la forma especificada aquí, se pueden usar
 * FormatterFactories. También se le puede usar setColumns
 */
public class NumberExample extends JFrame {
    private static final long serialVersionUID = 1L;

    private JLabel lblNumérico = new JLabel("Números");

    private JFormattedTextField txtObjeto = getTxtObjeto();

    private JFormattedTextField txtNumérico = getNumérico();

    private JLabel lblCadena = new JLabel("Cadenas");

    private JFormattedTextField txtCadena = getTexto();

    private JLabel lblFecha = new JLabel("Fechas");

    private JFormattedTextField txtFecha = getTxtFecha();

    public NumberExample() {
        super("Texto con Formato");
        setContentPane(new JScrollPane(getPanel()));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }

    private JPanel getPanel() {
        JPanel panel = new JPanel(new GridLayout(4, 2));
        panel.add(lblNumérico);
        panel.add(txtObjeto);
        panel.add(new JLabel());
        panel.add(txtNumérico);
        panel.add(lblCadena);
        panel.add(txtCadena);
        panel.add(lblFecha);
        panel.add(txtFecha);
        return panel;
    }
 
    /**
     * Devuelve un JFormattedTextField que captura datos del tipo del objeto que
     * recibe. Es la forma más simple de utilizar estos componentes.
     */
    private JFormattedTextField getTxtObjeto() {
        //Crea un campo de 6 columnas con un valor inicial numérico
        //entero.
        JFormattedTextField txtObjeto = new JFormattedTextField(new Integer(0));
        //Los campos numéricos normalmente se alínean a la derecha
        txtObjeto.setHorizontalAlignment(JFormattedTextField.TRAILING);
        //Este evento se activa al perder el foco u oprimir enter
        txtObjeto.addPropertyChangeListener("value",
                new PropertyChangeListener() {
                    public void propertyChange(PropertyChangeEvent evt) {
                        leeTxtObjeto();
                    }
                });
        return txtObjeto;
    }
 
    /**
     * Devuelve un JFormattedTextField que captura datos de tipo numérico
     * y obliga a que se respete la máscara de captura. Revisar la
     * especificación de la DecimalFormat para obtener el formato de
     * la máscara de captura.
     * En este esquema se usa un DecimalFormat para desplegar la información
     * capturada y un NumberFormatter para validar la información.
     * Para el DecimalFormat las cadenas tinen uno de dos formatos:
     * "formato de positivos;formato de negativos"
     * "formato de positivos" automáticamente los números negativos tienen el
     * mismo formato, pero le antepone el signo '-'. Los caracteres permitidos
     * son:
     * 0          | Dígito
     * #          | Dígito. Si no aparece, pone cero
     * .          | Separador decimal o de moneda
     * -          | Signo menos
     * ,          | Separador de grupo
     * E          | Separa mantisa del exponente en notación científica
     * ;          | separador de patrones para positivos y para negativos
     * %          | Multiplica por 100 y muestra como porcentaje
     * \u2030     | Multiplica por 1000 y muestra como valor por mil
     * ¤ (\u00A4) | Se reemplaza por el signo de la moneda
     * '          | Caracter de escape, por ejemplo, "'#'#"
     *            | formatea 123 como "#123". Para ' usa ''.
     */
    public static JFormattedTextField getNumérico() {
        DecimalFormat nf = new DecimalFormat("#.00");
        NumberFormatter formatter = new NumberFormatter(nf);
        formatter.setValueClass(Double.class);
        formatter.setMinimum(new Double(0.0));
        formatter.setMaximum(new Double(40000.0));
        formatter.setAllowsInvalid(false);
        JFormattedTextField texto = new JFormattedTextField(formatter);
        texto.setHorizontalAlignment(JFormattedTextField.TRAILING);
        return texto;
    }
    /**
     * Devuelve un JFormattedTextField que captura datos de tipo texto
     * y obliga a que se respete la máscara de captura. Revisar la
     * especificación de la MaskFormatter para obtener el formato de
     * la máscara de captura. Los caracteres permitidos en el formato
     * son:
     * # | Cualquier dígito. Usa Character.isDigit.
     * ' | Caracter de escape para cualquier caracter especial
     * U | Cualquier letra (Character.isLetter). Las minúsculas
     *   |    se convierten en mayúsculas.
     * L | Cualquier letra (Character.isLetter). Las mayúsculas
     *   |    se convierten en minúsculas.
     * A | Cualquier letra o número. (Character.isLetter o Character.isDigit)
     * ? | Cualquier letra (Character.isLetter).
     * * | Cualquier caracter.
     * H | Cualquier caracter hexadecimal (0-9, a-f or A-F).
     */
    public static JFormattedTextField getTexto() {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter("*****");
        } catch (ParseException e) {
            //Se llega a esta línea si la máscara no tiene el formato
            //correcto.
            e.printStackTrace();
        }
        JFormattedTextField texto = new JFormattedTextField(formatter);
        return texto;
    }
    /**
     * Devuelve un JFormattedTextField que captura datos de tipo fecha
     * y obliga a que se respete el formato especificado. Revisar la
     * especificación de la clase DateFormat para saber como configurar
     * el formato de la fecha. Se pueden crear con las siguientes
     * operaciones estáticas de DateFormat.
     * getDateInstance() - Obtiene un DateFormat solo para fechas con el
     *                  estilo por defecto para el locale por defecto.
     * getDateInstance(int estilo)- Obtiene un DateFormat solo para fechas
     *                  con el estilo indicado, para el locale por defecto.
     *                  El estilo puede ser
     *                  SHORT - completamente numérico como
     *                          12/13/52 o 3:30pm
     *                  MEDIUM - es más larga, como Jan 12, 1952
     *                  LONG - más larga, como January 12, 1952 o 3:30:32pm
     *                  FULL - completamente especificada, como
     *                          Tuesday, April 12, 1952 AD o 3:30:42pm PST.
     * getDateInstance(int estilo, Locale unLocale)
     * getDateTimeInstance() - Obtiene un DateFormat para fecha con hora,
     *                  con el estilo por defecto para el locale por defecto.
     * getDateTimeInstance(int estiloFecha, int estiloHora)
     * getDateTimeInstance(int estiloFecha,int estiloHora, Locale unLocale)
     * getInstance() - Obtiene un DateFormat para fecha con hora, que usa
     *                  el estilo SHORT para ambas y el locale por defecto.
     * getTimeInstance() - Obtiene un DateFormat para hora, con el estilo por
     *                  defecto para el locale por defecto.
     * getTimeInstance(int estilo)
     * getTimeInstance(int estilo, Locale unLocale)
     */
    private JFormattedTextField getTxtFecha() {
        DateFormat formato = DateFormat.getDateInstance();
        JFormattedTextField texto = new JFormattedTextField(formato);
        texto.setEditable(false);
        //Muestra la fecha de hoy
        texto.setValue(new Date());
        return texto;
    }

    public void leeTxtObjeto() {
        //Cuando el componente pierde el foco o se oprime enter,
        //Se invoca la instrucción commitEdit y se valida el
        //contenido. Si este no es válido, se descarta y regresa
        //al valor anterior.
        Number valor = (Number) txtObjeto.getValue();
        int nuevoValor = valor.intValue() * 2;
        //Cambia el valor
        txtCadena.setValue(String.valueOf(nuevoValor));
    }

    public static void muestra() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        NumberExample frame = new NumberExample();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                muestra();
            }
        });
    }
}

domingo, 17 de agosto de 2014

Descargar juego de tetris del gusano que crece en jcreator (Snake) que crece cuando come puntos




Este codigo es del juego snake me pareció muy interesante, me lo paso un amigo y lo quiero compartir con ustedes, interesante lo del punto al azar en el cuadro, funciona en jcreator y en netbeans  







Esta clase se llama Snake 



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class Snake extends JFrame implements KeyListener, Runnable {

    JPanel p1, p2;
    JButton[] lb = new JButton[200];
    JButton bonusfood;
    JTextArea t;
    int x = 500, y = 250, gu = 2, directionx = 1, directiony = 0, speed = 50, difference = 0, oldx, oldy, score = 0;
    int[] lbx = new int[300];
    int[] lby = new int[300];
    Point[] lbp = new Point[300];
    Point bfp = new Point();
    Thread myt;
    boolean food = false, runl = false, runr = true, runu = true, rund = true, bonusflag = true;
    Random r = new Random();
    JMenuBar mymbar;
    JMenu game, help, level;

    public void initializeValues() {
        gu = 3;//para tamaño inicial del gusano
        lbx[0] = 100;
        lby[0] = 150;
        directionx = 10;
        directiony = 0;
        difference = 0;
        score = 0;
        food = false;
        runl = false;
        runr = true;
        runu = true;
        rund = true;
        bonusflag = true;
    }

  Snake() {
        super("Snake");
        setSize(500, 330);
        //Create Menue bar with functions
        creatbar();
        //initialize all variables
        initializeValues();
        // Start of UI design
        p1 = new JPanel();
        p2 = new JPanel();
        // t will view the score
        t = new JTextArea("Score ==>" + score);
        t.setEnabled(false);
        t.setBackground(Color.BLACK);
        // snake have to eat bonousfood to growup
        bonusfood = new JButton();
        bonusfood.setEnabled(false);
        // will make first snake
        createFirstSnake();

        p1.setLayout(null);
        p2.setLayout(new GridLayout(0, 1));
        p1.setBounds(0, 0, x, y);
        p1.setBackground(Color.blue);
        p2.setBounds(0, y, x, 30);
        p2.setBackground(Color.RED);

        p2.add(t); // will contain score board
        // end of UI design
        getContentPane().setLayout(null);
        getContentPane().add(p1);
        getContentPane().add(p2);

        show();
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        addKeyListener(this);
        // start thread
        myt = new Thread(this);
        myt.start(); // go to run() method corremos el hilo
    }

   public void createFirstSnake() {
         // Initially the snake has small length 3
        for (int i = 0; i < 3; i++) {
            lb[i] = new JButton("lb" + i);
            lb[i].setEnabled(false);
            p1.add(lb[i]);
            lb[i].setBounds(lbx[i],lby[i], 10, 10);//los botones se muestran
// en el marco con valor inicial de lbx[0]=100 lby[0]=150 tamaño de 10x10)
            lbx[i + 1] = lbx[i] - 10;
            lby[i + 1] = lby[i];
        }
    }

    public void creatbar() {
        mymbar = new JMenuBar();

        game = new JMenu("Game");

        JMenuItem newgame = new JMenuItem("New Game");
        JMenuItem exit = new JMenuItem("Exit");

        newgame.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        reset();
                    }
                });

        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        game.add(newgame);
        game.addSeparator();
        game.add(exit);

        mymbar.add(game);

        level = new JMenu("Level");

        mymbar.add(level);

        help = new JMenu("Help");

        JMenuItem creator = new JMenuItem("Creator");
        JMenuItem instruction = new JMenuItem("Instraction");

        creator.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(p2, "Name :tu ");
            }
        });

        help.add(creator);
        help.add(instruction);
        mymbar.add(help);

        setJMenuBar(mymbar);
    }

    void reset() {
        initializeValues();
        p1.removeAll();

        myt.stop();

        createFirstSnake();
        t.setText("Score==>" + score);

        myt = new Thread(this);
        myt.start();
    }

    void growup() {//crecer
        lb[gu] = new JButton();
        lb[gu].setEnabled(false);
        p1.add(lb[gu]);
//para aparecer al azar un punto en el cuadro
        int a = 10 + (10 * r.nextInt(48));//ramdom para x
        int b = 10 + (10 * r.nextInt(23));//ramdom para y
        System.out.print("\nx"+a);
        System.out.print("\ny"+b);
        lbx[gu] = a;
        lby[gu] = b;
        lb[gu].setBounds(a, b, 10, 10);

        gu++;
    }
    // this method contains the logic to move the snake. player will define the derection
    // this method just forward the snake to the right derection which deriction is pressed
    // by the player.
    void moveForward() {
        for (int i = 0; i < gu; i++) {// o123 en total 4 pociciones dependiendo si no creece gu
            lbp[i] = lb[i].getLocation();
           
           System.out.print("\nlbp i=0 1<3 i++"+lbp[i]);
           System.out.print("\nlb "+lb[i]);
        }

        lbx[0] += directionx;//incrementa de 10 en10 en 10
          System.out.print("\nlbx"+lbx[0]);
        lby[0] += directiony;
          System.out.print("\nlby"+lby[0]);
        lb[0].setBounds(lbx[0], lby[0], 10, 10);

        for (int i = 1; i < gu; i++) {
            lb[i].setLocation(lbp[i-1 ]);//quitara la ultima pocicion de las 4 botones
           System.out.print("\nlb 1<3 i++ i-1"+lb[i]);
        }
//cuando llega al final inicia en el otro lado
        if (lbx[0] == x) {
            lbx[0] = 10;
          //    System.out.print("\nvector botones llego a la pared x=500"+x);
        } else if (lbx[0] == 0) {
            lbx[0] = x - 10;
          
        } else if (lby[0] == y) {
            lby[0] = 10;
      //      System.out.print("\nvector botones llego a la pared x="+y);
        } else if (lby[0] == 0) {
            lby[0] = y - 10;
        }

        if (lbx[0] == lbx[gu - 1] && lby[0] == lby[gu - 1]) {
            food = false;
            score += 5;
            t.setText("Score==>" + score);
            if (score % 50 == 0 && bonusflag == true) {
                p1.add(bonusfood);
                bonusfood.setBounds((10 * r.nextInt(50)), (10 * r.nextInt(25)), 15, 15);
                bfp = bonusfood.getLocation();
                bonusflag = false;
            }
        }

        if (bonusflag == false) {
            if (bfp.x <= lbx[0] && bfp.y <= lby[0] && bfp.x + 10 >= lbx[0] && bfp.y + 10 >= lby[0]) {
                p1.remove(bonusfood);
                score += 100;
                t.setText("Score ==>" + score);
                bonusflag = true;
            }
        }

        if (food == false) {
            growup();
            food = true;
        } else {
            lb[gu - 1].setBounds(lbx[gu - 1], lby[gu - 1], 10, 10);
        }

        for (int i = 1; i < gu; i++) {
            if (lbp[0] == lbp[i]) {
                t.setText("GAME OVER               " + score);
                try {
                    myt.join();
                } catch (InterruptedException ie) {
                }
                break;
            }
        }


        p1.repaint();
        show();
    }

    public void keyPressed(KeyEvent e) {
        //KeyCode() == 37 cada numero significa una tecla de direccion
        // snake move to left when player pressed left arrow
        if (runl == true && e.getKeyCode() == 37) {
            directionx = -10; // means snake move right to left by 10pixels
            directiony = 0;
            runr = false;     // run right(runr) means snake cant move from left to right
            runu = true;      // run up   (runu) means snake can move from down to up
            rund = true;      // run down (run down) means snake can move from up to down
        }
        // snake move to up when player pressed up arrow
        if (runu == true && e.getKeyCode() == 38) {
            directionx = 0;
            directiony = -10; // means snake move from down to up by 10 pixel
            rund = false;     // run down (run down) means snake can move from up to down
            runr = true;      // run right(runr) means snake can move from left to right
            runl = true;      // run left (runl) means snake can move from right to left
        }
        // snake move to right when player pressed right arrow
        if (runr == true && e.getKeyCode() == 39) {
            directionx = +10; // means snake move from left to right by 10 pixel
            directiony = 0;
            runl = false;
            runu = true;
            rund = true;
        }
        // snake move to down when player pressed down arrow
        if (rund == true && e.getKeyCode() == 40) {
            directionx = 0;
            directiony = +10; // means snake move from left to right by 10 pixel
            runu = false;
            runr = true;
            runl = true;
        }
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyTyped(KeyEvent e) {
    }

    public void run() {
        for (;;) {
            // Move the snake move forword. In the start of the game snake move left to right,
            // if player press up, down, right or left arrow snake change its direction according to
            // pressed arrow
            moveForward();
            try {
                Thread.sleep(speed);
            } catch (InterruptedException ie) {
            }
        }
    }

}


Esta esta es la clase principal para que funcione, Main.java
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Snake();
    }

}

domingo, 3 de agosto de 2014

Programas en java para novatos: conexion a base de datos. Crear un programa en java que guarde, elimine busque, y modifique datos en una base de datos de informacion la clientes, proveedores y productos, usando consultas las básicas en base de datos MySQL y hacer la conexión usando el conector java mysql-connector-java

Crear un programa en java que guarde, elimine busque, y modifique datos en una base de datos la informacion de clientes, proveedores y productos, usando consultas las básicas en base de datos MySQL y hacer la conexión usando el conector java mysql-connector-java 


En clientes se debe hacer las consultas de:
1.- Guardar Datos
2.- Ver Datos
3.-Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Clientes"

 En Productos  se debe hacer las consultas                    
 1.- Guardar Datos
 2.- Ver Datos
 3.- Modificar Datos
 4.- Eliminar Datos
 5.- Buscar datos
 6.- Salir de Productos

En Proveedor  se debe hacer las consultas        
 1.- Guardar Datos
 2.- Ver Datos
 3.- Modificar Datos
 4.- Eliminar Datos
 5.- Buscar datos
 6.- Salir de Productos

Si no tienes MySQL instalado  puedes ver como se instala aqui:
creamos la base de datos en MySQL

 CREATE DATABASE  practica_manuel         creamos la base de datos
USE practica_manuel;                          usamos esa base de datos
DROP TABLE IF EXISTS `cliente`;
CREATE TABLE `cliente` (                creamos las tablas a usar para la base de datos 
  `dni` int(11) default NULL,
  `nombre` varchar(30) default NULL,
  `apellidos` varchar(50) default NULL,
  `fecha_nacimiento` varchar(40) default NULL,
  `telefono` varchar(15) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

                                                            insertamos los datos en la tabla cliente
INSERT INTO `cliente` (`dni`,`nombre`,`apellidos`,`fecha_nacimiento`,`telefono`) VALUES
 (1,'manuel','cortes','21-11-89','123456');



DROP TABLE IF EXISTS `producto`;
CREATE TABLE `producto` (
  `codigo` int(11) default NULL,
  `nombre` varchar(30) default NULL,
  `precio` varchar(15) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `producto` (`codigo`,`nombre`,`precio`) VALUES
 (1,'leche','5');



DROP TABLE IF EXISTS `proveedor`;

CREATE TABLE `proveedor` (
  `nif` int(11) default NULL,
  `nombre` varchar(30) default NULL,
  `direccion` varchar(50) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `proveedor` (`nif`,`nombre`,`direccion`) VALUES
 (1,'jose','salinas 203');



creamos un archivo llamado menu en java usando jcreator. o en netbeans creamos un proyecto tipo java aplicacion y creamos el archivo llamado menu

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class menu {
                static int elegir;
                static InputStreamReader leer=new InputStreamReader(System.in);
                static BufferedReader isr=new BufferedReader(leer);
                public static String url="jdbc:mysql://localhost:3306/practica_manuel?user=root&password=12345";

                public static void main(String[] args)throws IOException {
                               menu();
                }

                private static void menu()throws IOException {

                               System.out.println("Elige la opcion");
                               System.out.println("1.- Cliente");
                               System.out.println("2.- Producto");
                               System.out.println("3.- Proveedor");
                               System.out.println("4.- Salir");

                               String a=isr.readLine();
                               elegir=Integer.parseInt(a);

                               switch(elegir){
                               case 1:
                               cliente();
                                               break;

                               case 2:
                                               producto();
                                               break;
                               case 3:
                                               proveedor();
                                               break;
                               case 4:
                               System.exit(0);
                                               break;
                               }

                }

                private static void cliente() throws IOException {
                               System.out.println("Estas en Cliente");
                               System.out.println("Elige la opcion");
                               System.out.println("1.- Guardar Datos");
                               System.out.println("2.- Ver Datos");
                               System.out.println("3.- Modificar Datos");
                               System.out.println("4.- Eliminar Datos");
                               System.out.println("5.- Buscar datos");
                               System.out.println("6.- Salir de Clientes");

                               String c=isr.readLine();
                                elegir=Integer.parseInt(c);
                               switch(elegir){
                               case 1:
                                               guarda_cliente();
                                               break;
                               case 2:
                                               buscar_cliente();
                                               break;
                               case 3:
                                               modificar_cliente();
                                               break;
                               case 4:
                                               eliminar_cliente();
                                               break;
                               case 5:
                                               busca_dato();
                                               break;
                               case 6:
                                               menu();
                                               break;

                               }
                }


                private static void busca_dato()throws IOException {

                               System.out.println("introduce el DNI del cliente para su busqueda");
                               String busca=isr.readLine();
                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM cliente where dni='"+busca+"'";



                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.print("" );
                                                               System.out.println("DNI  Nombre     Apellidos             Fecha de nacimiento      Telefono");
                                                                              System.out.print( rs.getString(1)+"    "+rs.getString(2)+"      "+rs.getString(3)+"                "+rs.getString(4)+"              "+rs.getString(5));
                                                               System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               cliente();
                }

                private static void eliminar_cliente() throws IOException{

                               System.out.println("Introduce el DNI del cliente para eliminar sus datos");
                               int dni=Integer.parseInt(isr.readLine());

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="delete from cliente where dni='"+dni+"'";
                                               int n=st.executeUpdate(query);
                     
                                               System.out.println("Se elimino " + n +" registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }

                               cliente();
                }

                private static void modificar_cliente()throws IOException {

                               try {

                               System.out.println("Teclea el DNI para modificar ");
                               int d=Integer.parseInt(isr.readLine());

                               System.out.println("Teclea el nombre del cliente para modificar");
                               String name=isr.readLine();

                               System.out.println("Teclea los apellidos para mdificar");
                               String apellidos=isr.readLine();

                               System.out.println("Introduce a fecha de nacimiento para modificar");
                               String fecha=isr.readLine();

                               System.out.println("Introduce el num de telefono para modificar");
                               String telefono=isr.readLine();

                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                               Connection con=DriverManager.getConnection(url);
                               Statement st=con.createStatement();
                               String query="update cliente set dni='"+d+"',nombre='"+name+"',apellidos='"+apellidos+"',fecha_nacimieto='"+fecha+"',telefono='"+telefono+"'";

                               int n=st.executeUpdate(query);
                               System.out.println("Se modifico " + n+" un registro en la base de datos");
                               con.close();
                }catch(InstantiationException e){
                               e.printStackTrace();
                }catch(IllegalAccessException e){
                               e.printStackTrace();
                }catch(ClassNotFoundException e){
                               e.printStackTrace();
                }catch(SQLException e){
                               e.printStackTrace();
                }
                cliente();


                }

                private static void buscar_cliente() throws IOException {
                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM cliente ";
                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.print("" );
                                                               System.out.println("DNI  Nombre     Apellidos             Fecha de nacimiento      Telefono");
                                                               System.out.print( rs.getString(1)+"    "+rs.getString(2)+"      "+rs.getString(3)+"                "+rs.getString(4)+"              "+rs.getString(5));
                                                               System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               System.out.println("Datos encontrados del cliente");
                cliente();
                }

                private static void guarda_cliente() throws IOException{
                               try{
                                               System.out.println("Teclea el DNI ");
                                               int d=Integer.parseInt(isr.readLine());

                                               System.out.println("Teclea el nombre del cliente");
                                               String name=isr.readLine();

                                               System.out.println("Teclea los apellidos");
                                               String apellidos=isr.readLine();

                                               System.out.println("Introduce a fecha de nacimiento");
                                               String fecha=isr.readLine();

                                               System.out.println("Introduce el num de telefono");
                                               int telefono=Integer.parseInt(isr.readLine());


                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="insert into cliente values ('"+ d +"','"+name.toString()+"','"+apellidos.toString()+"','"+fecha.toString()+"','"+telefono+"')";
                                               int n=st.executeUpdate(query);
                                               System.out.println("Se guardo " + n+" un registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               cliente();
                }

                private static void producto()throws IOException {
                               System.out.println("Estas en Productos");
                               System.out.println("Elige la opcion");
                               System.out.println("1.- Guardar Datos");
                               System.out.println("2.- Ver Datos");
                               System.out.println("3.- Modificar Datos");
                               System.out.println("4.- Eliminar Datos");
                               System.out.println("5.- Buscar datos");
                               System.out.println("6.- Salir de Productos");

                               String p=isr.readLine();
                                elegir=Integer.parseInt(p);
                               switch(elegir){
                               case 1:
                                               guarda_producto();
                                               break;
                               case 2:
                                               buscar_producto();
                                               break;
                               case 3:
                                               modificar_producto();
                                               break;
                               case 4:
                                               eliminar_producto();
                                               break;
                               case 5:
                                               busca_dato_producto();
                                               break;
                               case 6:
                                               menu();
                                               break;
                               }
                }

                private static void busca_dato_producto()throws IOException {

                               System.out.println("Ingrese el codigo del producto para su busqueda");
                               String busca=isr.readLine();
                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM producto where codigo='"+busca+"'";



                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.print("" );
                                                               System.out.println("codigo    Nombre       Precio");
                                                                              System.out.print( rs.getString(1)+"         "+rs.getString(2)+"        "+rs.getString(3));
                                                               System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               System.out.println("Productos encontrados");
                               producto();
                }

                private static void eliminar_producto()throws IOException {
                               System.out.println("Introduce el codigo del producto para eliminar ");
                               int codigo=Integer.parseInt(isr.readLine());

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="delete from producto where codigo='"+codigo+"'";
                                               int n=st.executeUpdate(query);
                                               System.out.println("Se elimino " + n +" registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               producto();
                }

                private static void modificar_producto()throws IOException {

                               try {

                                               System.out.println("Teclea el codigo del producto para modificar ");
                                               int codigo=Integer.parseInt(isr.readLine());

                                               System.out.println("Teclea el nombre del producto para modificar");
                                               String name=isr.readLine();

                                               System.out.println("Teclea el precio del producto para mdificar");
                                               String precio=isr.readLine();


                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="update producto set codigo='"+codigo+"',nombre='"+name+"',precio='"+precio+"'";

                                               int n=st.executeUpdate(query);
                                               System.out.println("Se modifico " + n+" un registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               producto();
                }

                private static void buscar_producto() throws IOException {
                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM producto ";
                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.print("" );
                                                               System.out.println("codigo    Nombre       Precio");
                                                               System.out.print( rs.getString(1)+"         "+rs.getString(2)+"        "+rs.getString(3));
                                                                              System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }

                               System.out.println("Productos encontrados");

                               producto();
                }

                private static void guarda_producto() throws IOException{

                               System.out.println("Insertar codigo del producto ");
                               int codigo=Integer.parseInt(isr.readLine());

                               System.out.println("Inserta nombre del producto");
                               String name=isr.readLine();

                               System.out.println("Insertar precio del producto");
                               int precio=Integer.parseInt(isr.readLine());

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="insert into producto values ('"+codigo+"','"+name.toString()+"','"+precio+"')";
                                               int n=st.executeUpdate(query);
                                               System.out.println("Se guardo " + n+" un registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }

                               producto();
                }

                private static void proveedor()throws IOException {
                               System.out.println("Estas en Proveedor");
                               System.out.println("Elige la opcion");
                               System.out.println("1.- Guardar Datos");
                               System.out.println("2.- Ver Datos");
                               System.out.println("3.- Modificar Datos");
                               System.out.println("4.- Eliminar Datos");
                               System.out.println("5.- Buscar datos");
                               System.out.println("6.- Salir de Productos");

                               String p=isr.readLine();
                                elegir=Integer.parseInt(p);
                               switch(elegir){
                               case 1:
                                               guarda_proveedor();
                                               break;
                               case 2:
                                               buscar_proveedor();
                                               break;
                               case 3:
                                               modificar_proveedor();
                                               break;
                               case 4:
                                               eliminar_proveedor();
                                               break;
                               case 5:
                                               busca_dato_proveedor();
                                               break;
                               case 6:
                                               menu();
                                               break;

                               }
                }

                private static void busca_dato_proveedor()throws IOException {
                               System.out.println("introduce el NIF del proveedor para su busqueda");
                               String busca=isr.readLine();
                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM proveedor where nif='"+busca+"'";



                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.print("" );
                                                               System.out.println("NIF     Nombre        Direccion");
                                                                              System.out.print( rs.getString(1)+"       "+rs.getString(2)+"            "+rs.getString(3));
                                                               System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               System.out.println("Proveedores encontrados");
                               proveedor();
                }

                private static void eliminar_proveedor()throws IOException {

                               System.out.println("Introduce el NIF del proveedor para eliminar sus datos");
                               int nif=Integer.parseInt(isr.readLine());

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="delete from proveedor where nif='"+nif+"'";
                                               int n=st.executeUpdate(query);
                                               System.out.println("Se elimino " + n +" registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               proveedor();
                }

                private static void modificar_proveedor()throws IOException {
                               try {

                                               System.out.println("Teclea el NIF del proveedor para modificar ");
                                               int nif=Integer.parseInt(isr.readLine());

                                               System.out.println("Teclea el nombre del proveedor para modificar");
                                               String name=isr.readLine();

                                               System.out.println("Teclea la direccion del proveedor para mdificar");
                                               String direccion=isr.readLine();

                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="update proveedor set nif='"+nif+"',nombre='"+name+"',direccion='"+direccion+"'";

                                               int n=st.executeUpdate(query);
                                               System.out.println("Se modifico " + n+" un registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                                }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               proveedor();
                }

                private static void buscar_proveedor() throws IOException {

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               String consulta="SELECT * ";
                                               consulta=consulta + "FROM proveedor ";
                                               System.out.println(consulta);
                                               PreparedStatement pSt= con.prepareStatement(consulta);
                                               ResultSet rs=pSt.executeQuery(consulta);
                                               while(rs.next()){
                                                               System.out.println("NIF     Nombre        Direccion");
                                                               System.out.print( rs.getString(1)+"       "+rs.getString(2)+"            "+rs.getString(3));

                                                               System.out.println("");
                                               }

                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }
                               System.out.println("Datos encontrados del proveedor");
                               proveedor();
                }

                private static void guarda_proveedor()throws IOException {

                               System.out.println("Teclea el NIF del proveedor ");
                               int nif=Integer.parseInt(isr.readLine());

                               System.out.println("Teclea el nombre del Proveedor");
                               String name=isr.readLine();

                               System.out.println("Teclea la direccion del proveedor");
                               String direccion=isr.readLine();

                               try{
                                               Class.forName("com.mysql.jdbc.Driver").newInstance();
                                               Connection con=DriverManager.getConnection(url);
                                               Statement st=con.createStatement();
                                               String query="insert into proveedor values ('"+nif+"','"+name.toString()+"','"+direccion.toString()+"')";
                                               int n=st.executeUpdate(query);
                                               System.out.println("Se guardo " + n+" un registro en la base de datos");
                                               con.close();
                               }catch(InstantiationException e){
                                               e.printStackTrace();
                               }catch(IllegalAccessException e){
                                               e.printStackTrace();
                               }catch(ClassNotFoundException e){
                                               e.printStackTrace();
                               }catch(SQLException e){
                                               e.printStackTrace();
                               }

                               proveedor();
                }



}


run:
Elige la opcion
1.- Cliente
2.- Producto
3.- Proveedor
4.- Salir
1
Estas en Cliente
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Clientes
1
Teclea el DNI
1
Teclea el nombre del cliente
juan
Teclea los apellidos
vazquez
Introduce a fecha de nacimiento
22-22-1990
Introduce el num de telefono
12345
Se guardo 1 un registro en la base de datos
Estas en Cliente
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Clientes
2
SELECT * FROM cliente
DNI  Nombre     Apellidos             Fecha de nacimiento      Telefono
1    juan      vazquez                22-22-1990              12345
Datos encontrados del cliente
Estas en Cliente
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Clientes
2
SELECT * FROM cliente
DNI  Nombre     Apellidos             Fecha de nacimiento      Telefono
1    juan      vazquez                22-22-1990              12345
Datos encontrados del cliente
Estas en Cliente
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Clientes
6
Elige la opcion
1.- Cliente
2.- Producto
3.- Proveedor
4.- Salir
2
Estas en Productos
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Productos
2
SELECT * FROM producto
codigo    Nombre       Precio
1         leche        5
codigo    Nombre       Precio
12         caca        123
Productos encontrados
Estas en Productos
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos
6.- Salir de Productos
5
Ingrese el codigo del producto para su busqueda
12
SELECT * FROM producto where codigo='12'
codigo    Nombre       Precio
12         caca        123
Productos encontrados
Estas en Productos
Elige la opcion
1.- Guardar Datos
2.- Ver Datos
3.- Modificar Datos
4.- Eliminar Datos
5.- Buscar datos

6.- Salir de Productos