Foro de elhacker.net

Programación => Java => Mensaje iniciado por: CorazonValiente en 9 Agosto 2008, 00:21 am



Título: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 9 Agosto 2008, 00:21 am
Saludos.

Es una de las herramientas que mas me gusta en Netbeans y quisiera conocer mas acerca de ellas, no soy un experto, pero apenas tenga tiempo colocare a dispocision mis conocimientos (En realidad es creatividad).

Pregunto: como puedo usar un jTable para tomar datos, ya saben como si fuera un jTextField.

BUEN DIA A TODOS LOS PROGRAMADORES



Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 9 Agosto 2008, 01:55 am
Saludos.

Es una de las herramientas que mas me gusta en Netbeans y quisiera conocer mas acerca de ellas, no soy un experto, pero apenas tenga tiempo colocare a dispocision mis conocimientos (En realidad es creatividad).

Pregunto: como puedo usar un jTable para tomar datos, ya saben como si fuera un jTextField.

BUEN DIA A TODOS LOS PROGRAMADORES




oye estas confundido el Jtable no es una herramienta del netbeans no tiene nada que ver

el lenguaje java es unico y ay un monton de porgramas que trabajon con el llamados ides (Jdeveloper, netbeans, Jcreator,etc ) este lenguaje tinene barias clases prediseñadas  por lo cual cualquier ide trabja con esas clases es decir que el Jdeveloper crea Jtables como lo ase el netbeans y todo el resto de los ides


bueno para resolver tu pregunta Como uso la clase Jtable que pertenece a java y que puede ser usado por cualquier ide no solo sea netbeans

primero se crea un defaulttablemodel con esto puedes sacar y meter datos de tu tabla y luego la tabla en si en el defaulttablemodel le ases los cambios

asi:

Código:
private DefaultTableModel modelo = new DefaultTableModel()
private JTable tabla = new JTable();

 
luego a tu tabla le dises cual es su modelo que forma tiene cuantas filas y columnas tienes

tabla.setModel(tablita);
tabla.setBounds(new Rectangle(10, 60, 510, 370));
modelo.setColumnCount(15);
modelo.setRowCount(15);

luego para meter y sacar datos se los ases en tu  defaulttablemodel
asi:

//poniendo los datos en la tabla se tiene que especificar fila y columna

Código:
modelo.setValueAt( dato ,fila ,columna );

//sacar datos de la tabla

Código:
modelo.getValueAt(fila ,columna);


Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 9 Agosto 2008, 02:02 am
temgo un monton de ejercicios echos con jtable pero no son muy faciles de comprender si quieres te lo mando


Título: Re: JTable - Todos sus posibles usos
Publicado por: -Ramc- en 9 Agosto 2008, 02:38 am
temgo un monton de ejercicios echos con jtable pero no son muy faciles de comprender si quieres te lo mando
Seria muy enriquecedor si subes tus códigos para que todos los veamos ;)


Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 10 Agosto 2008, 07:48 am
bueno como estoy con tiempo libre te boy a poner algunos ejemplos bien expicladitos

import java.awt.Dimension;

import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Frame1 extends JFrame{
    //mis varibles globales
   
    //esta es mi tabla
    JTable tablita=new JTable();
    /* */
   
    //este es mi modelo
    DefaultTableModel modelo=new DefaultTableModel();
    /* */
   
    public Frame1(){
    //contrusctor de la ventan
        try{
            jbInit();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }


    private void jbInit() throws Exception{
        //este metodo se aplica en mi contructor no es necesario crealo de esta forma
        //no todos los ides trabjan asi
        this.getContentPane().setLayout( null );
        this.setSize( new Dimension(400, 300) );
        this.setTitle("ejemplo uno");
        tablita.setBounds(new Rectangle(35,85,310,20));
        modelo.setColumnCount(16);
        modelo.setRowCount(1);
        this.getContentPane().add(tablita,null);
        //le desimos a mi tabla cual ba a hacer su modelo
       
        tablita.setModel(modelo);
       
        //lenamos balores a la tabla
        //ten en cuenta que la fila y la culmna comiensan en 0
        tablita.setValueAt("c",0,0);
        tablita.setValueAt("o",0,1);
        tablita.setValueAt("r",0,2);
        tablita.setValueAt("a",0,3);
        tablita.setValueAt("s",0,4);
        tablita.setValueAt("o",0,5);
        tablita.setValueAt("n",0,6);
        tablita.setValueAt("",0,7);
        tablita.setValueAt("b",0,8);
        tablita.setValueAt("a",0,9);
        tablita.setValueAt("l",0,10);
        tablita.setValueAt("i",0,11);
        tablita.setValueAt("e",0,12);
        tablita.setValueAt("n",0,13);
        tablita.setValueAt("t",0,14);
        tablita.setValueAt("e",0,15);
       
    }
    public  static void main(String[] args){
        JFrame frame=new Frame1();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 10 Agosto 2008, 08:02 am
justo que esta busacando aca te pongo un link
http://ji.ehu.es/LMAlonso/SW/java/Bib/tutorjava/html/ui/swingcomponents/table.html


Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 16 Agosto 2008, 00:03 am
Gracias; es muy interensante, estoy entre personas que manejan mucho mas la programacion que yo, sigan dando sus opiniones, sus consejos los usos para idear pequeñas aplicaciones.

Para mostrar datos en una tabla siempre uso vectores y matrices asi:

import javax.swing.JTable;
private void jTable1AncestorAdded(javax.swing.event.AncestorEvent evt) {                                     
               
        Procedimientos op=new Procedimientos();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            op.Matrix(),
            new String [] {"Nombre", "Modelo", "Rendimiento x galon",
                                   "Precio", "Cantidad"}
        ));
       
    }   

QUERIA ADJUNTARLES LA APLICACION COMPLETA PERO NO ENCONTRE COMO: ;D


Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 16 Agosto 2008, 20:57 pm
no te preocupes copia y pega toda la clase completa
nosotros  lo compilamos y ejecutamos facil


Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 19 Agosto 2008, 17:36 pm
Saludos.

Como dije al inicio no soy muy experimentado en la programacion, les mando un sencillo codigo de como hago para introducir datos en una tabla.

=================================================
/*
 * main.java
 *
 * Created on 3 de agosto de 2008, 04:26 PM
 */



/**
 *
 * @author  Rey Salcedo
 */
public class main extends javax.swing.JFrame {
   
    /** Creates new form main */
    public main() {
        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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "nombre", "apellidos", "cedula", "telefono", "direcion"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("VER");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"tania", "olivero", "231343432", "7762562", "uiwuriwr"},
                {"rey", "salcedo", "78076126", "757575", "dhjash"},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "nombre", "apellidos", "cedula", "telefono", "direcion"
            }
        ));
    }                                       
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main().setVisible(true);
            }
        });
    }
   
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
   
}

===========================================
 ;D


Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 19 Agosto 2008, 18:07 pm
Aprovecho, con el codigo que coloque; como pueden ver si hacen clic en el boton me muestra unos datos;

Me gustaria saber como hace lo inverso, es decir introducir datos en la tabla, hacer clic en el boton y guardar los datos en la matrix.

 ;) ;)


Título: Re: JTable - Todos sus posibles usos
Publicado por: sapito169 en 21 Agosto 2008, 02:05 am
no es nesesario obtener la matris de Jtable

puedes obtener los datos de esta forma


modelo.getValueAt(fila,columna);


Código:
import java.awt.Dimension;

import java.awt.Rectangle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Frame1 extends JFrame {
    private JButton jButton1 = new JButton();
   
    //creo una nueba tabla y la instancio
    private JTable tabla = new JTable();
    //
   
    //creo un nuevo modelo para mi tabla y lo instancio
    private DefaultTableModel modelo = new DefaultTableModel();
    //
   
    public Frame1() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        //este codigo ba dentro del constructor de la clase
       
       
        // este codigo lo ase automatico el ide
        this.getContentPane().setLayout( null );
        this.setSize( new Dimension(400, 300) );
        jButton1.setText("captura en fila 2 columna 3");
        jButton1.setBounds(new Rectangle(35, 185, 255, 45));
       
        jButton1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        jButton1_actionPerformed(e);
                    }
                });
        tabla.setBounds(new Rectangle(35, 20, 320, 145));
        this.getContentPane().add(tabla, null);
        this.getContentPane().add(jButton1, null);
        //
       
       
        //le deismos la cantidad de columnas y filas de mi modelo
        modelo.setColumnCount(4); /*columnas */
        modelo.setRowCount(3);/* filas*/
        //
       
       
        //le desimos a la tabla cual ba a ser su modelo
        tabla.setModel(modelo);
        //
        this.setVisible(true);
    }

    private void jButton1_actionPerformed(ActionEvent e) {
   
    // obtenemos el valor utilisando getvalueat en el modelo
    String a =modelo.getValueAt((3-1),(2-1)).toString();/* este metodo nos devuelve un objeto del tipod object*/
                                                        /* y lo pasamos a strihng*/   
   
   
    //recuerda que las filas y columnas enpiesan en 0 por eso restamos uno
    JOptionPane.showMessageDialog(null,"fila 3 columna 2 "+a);
    //
    }
   
    public static void main(String[] args){
        new Frame1();
    }
}



Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 21 Agosto 2008, 19:03 pm
Amigo sapito169; gracias has sabido responder mi pregunta, estoy emocionado,ahora que me desocupe que algunas cosas que tengo que hacer en el trabajo, le doy duro a tu codigo.

CorazonValiente muy agradecido  ;D


Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 21 Agosto 2008, 19:10 pm
Voy a compartir codigos de algo que hice y utilice tablas, por si alquien encuentras algo util dentro de el...
Notta: todas las clases van dentro del mismo procedimiento.
          Separo las clases con esta doble raya =============

====================================================

import java.io.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Rey Salcedo
 */
import javax.swing.*;
public class Procedimientos {

    public Procedimientos(){
       
    }
   
    int saldocantidad;
    String a,b,c,d,e,cantinicial;
   
    public int SetCantidadInicial(){
        return Integer.parseInt(cantinicial);
    }
   
    public String SetA(){
        return a;
    }
    public String SetB(){
        return b;
    }
    public String SetC(){
        return c;
    }
    public String SetD(){
        return d;
    }
    public String SetE(){
        return e;
    }
    public int SetSaldoCantidad(){
        return saldocantidad;
    }
    public String minusculas(String cadena){
        String Cadena=cadena.toLowerCase();
        return Cadena;
    }
    public boolean CaracterEspecial(String a){
    boolean valor=true;
        for (int i=0;i<a.length();i++){
            String Char =a.charAt(i)+"";
            if (Char.equals(";")){
                valor=false;
            }
        }
    return valor;
    }
   
    public void IngresarVehiculo(String dato){
        File Archivo = new File("Datos_vehiculo.txt");
        try{
        FileWriter EscribirArchivo =new FileWriter(Archivo,true);   
        BufferedWriter buffer = new BufferedWriter(EscribirArchivo);
        buffer.write(dato);
        buffer.newLine();
        buffer.close();
       
        }catch(Exception Ex){
         
        }
       
    }
   
   
    public void actualizarProducto(String a, String b,String c,String d,String e){
      //archivo productos.txt donde se encuentra la informacion de los productos
      File archivo=new File("Datos_vehiculo.txt");
      //archivo temp.txt = archivo temporal para realizar la actualizacion de la informacion
      File temp=new File("temp.txt");
       try{
        // se abre el archivo productos de lectura   
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        //se abre el archivo temp de escritura para pasar los registros desde el archivo productos.txt
        FileWriter archivoEscritura=new FileWriter(temp);
        BufferedWriter bufferTemp=new BufferedWriter(archivoEscritura);       
        String linea="";
        // se recorren todos los registros del archivo principal productos.txt
        while((linea=buffer.readLine())!=null){
           String[] registro=linea.split(";");
           //si el nombre del registro es igual al que se va a actualizar se agrega un registros
           //con el nombre del producto y el nuevo precio del producto sino se agrega el mismo registro
           // que se encuentra en el registro sin cambios
           if(registro[0].equals(a)){
             bufferTemp.write(registro[0]+";"+b+";"+c+";"+d+";"+e);
           }else
           {
             bufferTemp.write(linea); 
           }   
           bufferTemp.newLine();
        }
        //se cierran los dos archivos el temp.txt y productos.txt
        buffer.close();
        bufferTemp.close();
        //se elimina el archivo productos.txt
        archivo.delete();
        //se renombra el archivo temp.txt a productos.txt para convertirlo en el archivo principal
        temp.renameTo(archivo);
       }catch(Exception ex){
        ex.printStackTrace();
       }           
    }   
   
    public void Venta(String nombre, String cantidad){
        cantinicial="";
        boolean valor=false;
        File archivo=new File("Datos_vehiculo.txt");
      //archivo temp.txt = archivo temporal para realizar la actualizacion de la informacion
      File temp=new File("temp.txt");
       try{
        // se abre el archivo productos de lectura   
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        //se abre el archivo temp de escritura para pasar los registros desde el archivo productos.txt
        FileWriter archivoEscritura=new FileWriter(temp);
        BufferedWriter bufferTemp=new BufferedWriter(archivoEscritura);       
        String linea="";
        // se recorren todos los registros del archivo principal productos.txt
        while((linea=buffer.readLine())!=null){
           String[] registro=linea.split(";");
           //si el nombre del registro es igual al que se va a actualizar se agrega un registros
           //con el nombre del producto y el nuevo precio del producto sino se agrega el mismo registro
           // que scuentra en el registro sin cambios
           int cantmoto=(Integer.parseInt(registro[4])-Integer.parseInt(cantidad));
           
           if(registro[0].equals(nombre)){
              cantinicial= registro[4];
              d=registro[3];
              int Cantmoto;
              if(cantmoto>0){
                  Cantmoto=cantmoto;
                  valor=true;
              }else{
                  Cantmoto=0;
                  valor=false;
              }
           bufferTemp.write(registro[0]+";"+registro[1]+";"+registro[2]+";"+registro[3]+";"+Cantmoto);
                e=""+Cantmoto;
           }else
           {
             bufferTemp.write(linea); 
           }
           
           bufferTemp.newLine();
        }
       
        //se cierran los dos archivos el temp.txt y productos.txt
        buffer.close();
        bufferTemp.close();
        //se elimina el archivo productos.txt
        archivo.delete();
        //se renombra el archivo temp.txt a productos.txt para convertirlo en el archivo principal
        temp.renameTo(archivo);
       }catch(Exception ex){
        ex.printStackTrace();
       }
     
    }
       
    public boolean haber(String nombre, String cantidad){
        boolean valor=false;
        File archivo=new File("Datos_vehiculo.txt");
       try{
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        String linea="";
        while((linea=buffer.readLine())!=null){
           String[] registro=linea.split(";");
          int cantmoto=(Integer.parseInt(registro[4])-Integer.parseInt(cantidad));
           
           if(registro[0].equals(nombre)){
             if(cantmoto>0){
               valor=true;
              }else{
               valor=false;
              }
           }
         }
        buffer.close();
        }catch(Exception ex){
        ex.printStackTrace();
       }
      return valor;
    }
   
    public boolean buscarProducto(String nombre){
      String precio=""; 
      File archivo=new File("Datos_vehiculo.txt");
      boolean salida=true;
      try{
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        String linea="";
       
        while((linea=buffer.readLine())!=null && salida){
           String[] registro=linea.split(";");
           if(registro[0].equals(nombre)){
             a=registro[0];
             b=registro[1];
             c=registro[2];
             d=registro[3];
             e=registro[4];
             salida=false;
           }   
        }
        buffer.close();
       }catch(Exception ex){
        ex.printStackTrace();
       }     
      return salida;
    }   
   
    public int longitud() {
        File archivo=new File("Datos_vehiculo.txt");
        int cont=0;
        try{
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        String linea="";
       
        while((linea=buffer.readLine())!=null){
           cont++;
        }
        }catch(Exception ex){
        ex.printStackTrace();
       }
        return cont;
    }
   
    public String[][] Matrix(){
        int L=longitud();
        String matrix[][]=new String[L][5];
        File archivo=new File("Datos_vehiculo.txt");
      try{
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        String linea="";
       int filas=0;
        while((linea=buffer.readLine())!=null){
           
           //for (int i=0;i<L;i++){
               String[] registro=linea.split(";");
               for (int j=0;j<5;j++){
                   matrix[filas][j]=registro[j];
               }
          // }
               filas++;   
        }
        buffer.close();
       }catch(Exception ex){
        ex.printStackTrace();
       }     
      return matrix;
  }
   
    public boolean MensajeModelo(String b,String c,String d,String e){
        boolean valor=true;
        try{
          int entero =Integer.parseInt(b);
          int entero1 =Integer.parseInt(c);
          int entero2 =Integer.parseInt(d);
          int entero3 =Integer.parseInt(e);
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null,"Los campos modelo, rendimiento, precio y cantidad son de tipo numerico; intente nuevamente","Mensaje",2);
            valor=false;
        }
        return valor;
    }
    public void eliminarProducto(String nombre){
      //archivo productos.txt donde se encuentra la informacion de los productos
      File archivo=new File("Datos_vehiculo.txt");
      //archivo temp.txt = archivo temporal para realizar la actualizacion de la informacion
      File temp=new File("temp.txt");
       try{
        // se abre el archivo productos de lectura   
        FileReader archivoLectura=new FileReader(archivo);
        BufferedReader buffer=new BufferedReader(archivoLectura);
        //se abre el archivo temp de escritura para pasar los registros desde el archivo productos.txt
        FileWriter archivoEscritura=new FileWriter(temp);
        BufferedWriter bufferTemp=new BufferedWriter(archivoEscritura);       
        String linea="";
        // se recorren todos los registros del archivo principal productos.txt
        while((linea=buffer.readLine())!=null){
           String[] registro=linea.split(";");
           //si el registro tiene el mismo nombre del producto a eliminar no se agrega al nuevo archivo
           if(!registro[0].equals(nombre)){           
             bufferTemp.write(linea); 
             bufferTemp.newLine();
           }   
           
        }
         //se cierran los dos archivos el temp.txt y productos.txt
        buffer.close();
        bufferTemp.close();
        //se elimina el archivo productos.txt
        archivo.delete();
        //se renombra el archivo temp.txt a productos.txt para convertirlo en el archivo principal
        temp.renameTo(archivo);
       }catch(Exception ex){
        ex.printStackTrace();
       }           
    }   
}

===========================================================

import javax.swing.JOptionPane;

/*
 * Vender.java
 *
 * Created on 5 de junio de 2008, 05:34 AM
 */



/**
 *
 * @author  Rey Salcedo
 */
public class Vender extends javax.swing.JFrame {
   
    /** Creates new form Vender */
    public Vender() {
        initComponents();
    }
 String [][]MatrixdeVenta;   
    /** 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() {

        jPanel1 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        jPanel1.setBorder(new javax.swing.border.MatteBorder(null));

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Cantidad:");

        jLabel1.setText("Vehiculo a vender:");

        jLabel3.setText("V   E   N   T   A");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel3)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(5, 5, 5)
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        jButton1.setText("Realizar venta");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Arial", 0, 14));
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setText("Atras");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jButton1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton1)
                    .add(jButton2))
                .add(11, 11, 11)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                       

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                           

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Procedimientos op = new Procedimientos();
             
        String n,c;
        n=op.minusculas(jTextField1.getText());
        c=op.minusculas(jTextField2.getText());
               
        boolean valor1=true;
        try{
        int temp=Integer.parseInt(c);
        }catch(Exception ex){
           
            valor1=false;
            jTextField2.setText("");
           
        }
        if (valor1){//es verdadero si no se produce la excepcion
            boolean valor2=op.haber(n, c); //es verdadero si existen suficientes vehiculo para vender
            if (valor2){
                //si existen autos suficientes hará esto
                    op.Venta(n, c);
                    jTextField1.setText("");
                    jTextField2.setText("");
                    int ValorVenta= Integer.parseInt(c)*Integer.parseInt(op.SetD());
         
           
                    jTextArea1.setText("¡LA VENTA HA SIDO UN EXITO!\n"
                    +"----------------DETALLE----------------\n"
                    +"Nombre: "+n+"\n"
                    + "Cantidad vendida: "+c+"\n"
                    +"Cantidad vehiculos por vender: "+op.SetE()+"\n"
                    +"La venta asciende a la suma de $"+ValorVenta);
         
            }else{
           //si no existen autos suficientes hará esto otro}
           //     int opcion = JOptionPane.showConfirmDialog(this,"Solo hay "+op.SetCantidadInicial()+" vehiculo(s) para vender; desea aun asi realizar la venta?", "Vender",JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
       
           //     if (opcion == JOptionPane.YES_OPTION) {
                op.Venta(n, c);
                jTextField1.setText("");
                jTextField2.setText("");
                int ValorVenta=(Integer.parseInt(c)-op.SetCantidadInicial())*Integer.parseInt(op.SetD());
                jTextArea1.setText("¡LA VENTA HA SIDO UN EXITO!\n"
                   +"----------------DETALLE----------------\n"
                   +"Se vendieron solo "+op.SetCantidadInicial()+" de "+c+"\n"
                   +"Nombre: "+n+"\n"
                   + "Cantidad vendida: "+op.SetCantidadInicial()+"\n"
                   +"Cantidad vehiculos por vender: "+0+"\n"
                   +"La venta asciende a la suma de $"+ValorVenta);
          //  }
            }
        }else{
        //este else es si se produce la excepcion
        JOptionPane.showMessageDialog(null,"El precio debe ser un valor numerico","Mensaje",2);   
        }
       
             
    }                                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Main main=new Main();
        this.hide();
        main.show();
    }                                       
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Vender().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;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                   
   
}
================================================

import javax.swing.JTable;

/*
 * NewJFrame.java
 *
 * Created on 5 de junio de 2008, 04:31 AM
 */



/**
 *
 * @author  Rey Salcedo
 */
public class Mostrar extends javax.swing.JFrame {
   
    /** Creates new form NewJFrame */
    public Mostrar() {
        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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Nombre", "Modelo", "Rendimiento x galon", "Precio", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
                jTable1AncestorAdded(evt);
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Atras");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 242, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1)
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
       
       
       
       
    }                                   

    private void jTable1AncestorAdded(javax.swing.event.AncestorEvent evt) {                                     
        // TODO add your handling code here:
       
        Procedimientos op=new Procedimientos();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            op.Matrix(),
            new String [] {"Nombre", "Modelo", "Rendimiento x galon",
                                   "Precio", "Cantidad"}
        ));
       
    }                                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.hide();
        Main op = new Main();
        op.show();
       
    }                                       

    private void formMouseReleased(java.awt.event.MouseEvent evt) {                                   
        // TODO add your handling code here:
       
    }                                 
   
    /**
     * @param args the command line arguments
     */
    public  void mostrar(){
       
        Procedimientos op=new Procedimientos();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            op.Matrix(),
            new String [] {"Nombre", "Modelo", "Rendimiento x galon",
                                   "Precio", "Cantidad"}
        ));
       
       
       
               
    }
   
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Mostrar().setVisible(true);
               
       
               
            }
        });
       
         
       
    }
   
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
   
}
================================================


Título: Re: JTable - Todos sus posibles usos
Publicado por: CorazonValiente en 21 Agosto 2008, 19:34 pm
Este es el Main que le hice a la aplicacion anterior.

El programa guarda los datos por medio de una archivo *.csv
==================================================
/*
 * Main.java
 *
 * Created on 31 de mayo de 2008, 04:55 AM
 */



/**
 *
 * @author  Rey Salcedo
 */
import javax.swing.*;
public class Main extends javax.swing.JFrame {
   
    /** Creates new form Main */
    public Main() {
        initComponents();
       
    }
   
    private void Limpiar(){
      jTextField1.setText("");
      jTextField2.setText("");
      jTextField3.setText("");
      jTextField4.setText("");
      jTextField5.setText("");
    }
    private void Restaurar(){
      jLabel1.setText("Nombre");
      jLabel2.setText("Modelo");
      jLabel3.setText("Rendimiento x galon");
      jLabel4.setText("Precio");
      jLabel5.setText("Cantidad");
      jTextField1.setEnabled(true);
      jTextField2.setEnabled(true);
      jTextField3.setEnabled(true);
      jTextField4.setEnabled(true);
      jTextField5.setEnabled(true);
      jButton1.setEnabled(true);
      jButton2.setEnabled(true);
      jButton3.setEnabled(true);
      jButton4.setEnabled(true);
      jButton5.setEnabled(true);
      jButton6.setEnabled(true);
      jButton7.setEnabled(true);
      jButton8.setEnabled(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() {

        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButton8 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ContaVehiculo-Free IDE 1.0");
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                formMouseExited(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(24, 240, 240));
        jPanel1.setBorder(new javax.swing.border.MatteBorder(null));

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField1FocusGained(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        jTextField5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField5ActionPerformed(evt);
            }
        });

        jLabel1.setText("Nombre");

        jLabel2.setText("Modelo");

        jLabel3.setText("Rendimiento x galon");

        jLabel4.setText("Precio");

        jLabel5.setText("Cantidad");

        jLabel6.setFont(new java.awt.Font("Arial", 0, 24));
        jLabel6.setText("Datos automovil");

        jButton8.setText("Limpiar");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jLabel4)
                            .add(jLabel5)
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jTextField5)
                            .add(jTextField4)
                            .add(jTextField3)
                            .add(jTextField2)
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(80, 80, 80)
                        .add(jLabel6))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton8))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel6)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 19, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .add(14, 14, 14)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(17, 17, 17)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(jTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(jTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jButton8)
                .add(4, 4, 4))
        );

        jPanel2.setBackground(new java.awt.Color(40, 240, 240));
        jPanel2.setBorder(new javax.swing.border.MatteBorder(null));

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Actualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Eliminar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Buscar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Venta");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("Mostrar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setText("Salir");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Arial", 0, 13));
        jLabel7.setText("Operaciones");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel7)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel7)
                .add(24, 24, 24)
                .add(jButton1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton5)
                .add(4, 4, 4)
                .add(jButton6)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton7)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(11, 11, 11)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                           

    private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                           

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                           

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                           

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Procedimientos pro = new Procedimientos();
        String a,b,c,d,e;
        boolean agregar;
        a=pro.minusculas(jTextField1.getText());
        b=pro.minusculas(jTextField2.getText());
        c=pro.minusculas(jTextField3.getText());
        d=pro.minusculas(jTextField4.getText());
        e=pro.minusculas(jTextField5.getText());
       
        boolean v=pro.buscarProducto(a);
      if(!a.equals("")){
        if (v){
            boolean valor =pro.MensajeModelo(b, c, d, e);
            if (valor){
                 boolean v2=pro.CaracterEspecial(a);
                if (v2){
                    pro.IngresarVehiculo(a+";"+b+";"+c+";"+d+";"+e);
                    JOptionPane.showMessageDialog(null,"Los datos del vehiculo "+a+" han sido agregados","Mensaje",2);
                    Limpiar(); 
                }else{
                    JOptionPane.showMessageDialog(null,"No es permitido usar el caracter (;), intente nuevamente","Mensaje",2);
                }
               
            }
        }else{
            JOptionPane.showMessageDialog(null,"Este vehiculo ya existe, intente actualizando","Mensaje",2);
        jTextField1.setText(a);
        jTextField2.setText(pro.SetB());
        jTextField3.setText(pro.SetC());
        jTextField4.setText(pro.SetD());
        jTextField5.setText(pro.SetE());
       
        }
      }else{
          JOptionPane.showMessageDialog(null,"Digite el nombre del vehiculo","Mensaje",2); 
      }   
    }                                       

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Procedimientos pro = new Procedimientos();
        String g="";
        g =pro.minusculas(JOptionPane.showInputDialog("Digite el vehiculo a buscar"));
        boolean valor=pro.buscarProducto(g);
       
        if (!valor){
            jTextField1.setText(pro.SetA());
            jTextField2.setText(pro.SetB());
            jTextField3.setText(pro.SetC());
            jTextField4.setText(pro.SetD());
            jTextField5.setText(pro.SetE());
            JOptionPane.showMessageDialog(null,"Busqueda finalizada, desde el resultado puedes eliminar y/o actualizar","Mensaje",2);
        }else{
            JOptionPane.showMessageDialog(null,"El vehiculo buscado no esta en inventario","Mensaje",2);
        }
    }                                       

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.hide();
        Mostrar op = new Mostrar();
        op.show();
       
    }                                       

    private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {                                       
        // TODO add your handling code here:
    }                                       

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
     //   Limpiar();
       
       
       
    }                                       

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Procedimientos pro = new Procedimientos();
       
        String a,b,c,d,e;
        a=pro.minusculas(jTextField1.getText());
        b=pro.minusculas(jTextField2.getText());
        c=pro.minusculas(jTextField3.getText());
        d=pro.minusculas(jTextField4.getText());
        e=pro.minusculas(jTextField5.getText());
        boolean v=pro.buscarProducto(a);
        if (!v){
            boolean valor =pro.MensajeModelo(b, c, d, e);
            if(valor){
                pro.actualizarProducto(a, b, c, d, e);
                JOptionPane.showMessageDialog(null,"El vehiculo "+a+" ha sido actualizado","Mensaje",2);
            }
        }else{
            JOptionPane.showMessageDialog(null,"El vehiculo "+a+" no se puede actualizar, no existe en inventario; ¡rectifique!","Mensaje",2);
        }
       
    }                                       

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
int opcion = JOptionPane.showConfirmDialog(this,"En realidad desea salir de la aplicación. ¿Continuar?", "Salir",JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (opcion == JOptionPane.YES_OPTION) {
this.dispose();//te cierra la ventana
}else{
//¿¿¿AQUI QUE IRIA PARA QUE NO TE LA CIERRE???
}
     
    }                                       

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
       
       
Procedimientos pro = new Procedimientos();
        String a;
        a = pro.minusculas(jTextField1.getText());
     
            String g =pro.minusculas(JOptionPane.showInputDialog("Digite el vehiculo a eliminar"));
            if (!pro.buscarProducto(g)){
                if (pro.CaracterEspecial(g)){
                   
                    int opcion = JOptionPane.showConfirmDialog(this,"El registro será eliminado de manera definitiva. ¿desea continuar?", "Salir",JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (opcion == JOptionPane.YES_OPTION) {
                        pro.eliminarProducto(g);
                        JOptionPane.showMessageDialog(null,"El vehiculo "+g+" ha sido eliminado","Mensaje",2);   
                    }else{
                    //¿¿¿AQUI QUE IRIA PARA QUE NO TE LA CIERRE???
                    }
                   
                   
                }else{
                    JOptionPane.showMessageDialog(null,"No se aceptar el caracter (;), !VERIFICA¡","Mensaje",2);   
                }
               
            }else{
               
                JOptionPane.showMessageDialog(null,"El vehiculo "+a+" no esta en inventario","Mensaje",2);
            }
            Limpiar();
   

       
       
       
    }                                       
boolean interruptor=true;
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
     this.hide();
     Vender op =new Vender();
     op.show();
    }                                       

    private void formMouseExited(java.awt.event.MouseEvent evt) {                                 
        // TODO add your handling code here:
       
    }                               
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
   
    // 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.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration                   
   
}