Foro de elhacker.net

Programación => Java => Mensaje iniciado por: hack-4-life en 20 Marzo 2011, 00:14 am



Título: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
Publicado por: hack-4-life en 20 Marzo 2011, 00:14 am
Buenas xd a toda la comunidad,queria ver si me podian ayudar,a ordenar estos 2 archivos,bueno!tengo un JTable conectado a la base de datos,,tengo un JTextField y tengo un JButton,lo que intento  hacer es filtrar texto desde un JTextField....

en este primer archivo me corre una jtable con unos datos por default,escribo en el jtextfield y le doy buscar y me encuentra lo que anote en el jtextfield con  sorter.setRowFilter ( RowFilter.regexFilter ( text )) ;,pero el PROBLEMA  es que sto no esta coenctada a la base de datos y se me vino a la mente que esta funcion la puedo ocupar para buscar datos en un jtable donde si tengo implementado la conexion desde una base de datos,si alguien me pudiera ayudar a implementarlo este es el archivo donde filtra el texto:
Código
  1. import java.awt.BorderLayout;
  2.   import java.awt.event.ActionEvent;
  3.   import java.awt.event.ActionListener;
  4.  
  5.   import javax.swing.JButton;
  6.   import javax.swing.JFrame;
  7.   import javax.swing.JLabel;
  8.   import javax.swing.JPanel;
  9.   import javax.swing.JScrollPane;
  10.   import javax.swing.JTable;
  11.   import javax.swing.JTextField;
  12.   import javax.swing.RowFilter;
  13.   import javax.swing.table.DefaultTableModel;
  14.   import javax.swing.table.TableModel;
  15.   import javax.swing.table.TableRowSorter;
  16.  
  17.    public class RegexTable {
  18.       public static void main ( String args []) {
  19.         JFrame frame = new JFrame ( "BUSCAR EN UN JTABLE" ) ;
  20.         frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ;
  21.         Object rows [][] = { { "A" , "About" , 44.36 } , { "B" , "Boy" , 44.84 } , { "C" , "Cat" , 463.63 } ,
  22.               { "D" , "Day" , 27.14 } , { "E" , "Eat" , 44.57 } , { "F" , "Fail" , 23.15 } ,
  23.               { "G" , "Good" , 4.40 } , { "H" , "Hot" , 24.96 } , { "I" , "Ivey" , 5.45 } ,
  24.               { "J" , "Jack" , 49.54 } , { "K" , "Kids" , 280.00 } } ;
  25.         String columns [] = { "NOMBRE" , "DESCRIPCION" , "PRECIO" } ;
  26.         TableModel model =
  27.             new DefaultTableModel ( rows, columns ) {
  28.                public Class getColumnClass ( int column ) {
  29.                  Class returnValue;
  30.                  if (( column >= 0 ) && ( column < getColumnCount ())) {
  31.                     returnValue = getValueAt ( 0 , column ) .getClass () ;
  32.                  }
  33.                  else {
  34.                     returnValue = Object. class ;
  35.                  }
  36.                  return returnValue;
  37.               }
  38.            } ;
  39.  
  40.         final JTable table = new JTable ( model ) ;
  41.         final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel> ( model ) ;
  42.         table.setRowSorter ( sorter ) ;
  43.         JScrollPane pane = new JScrollPane ( table ) ;
  44.         frame.add ( pane, BorderLayout.CENTER ) ;
  45.  
  46.         JPanel panel = new JPanel ( new BorderLayout ()) ;
  47.         JLabel label = new JLabel ( "REGISTRO" ) ;
  48.         panel.add ( label, BorderLayout.WEST ) ;
  49.         final JTextField filterText = new JTextField ( "Registro a Buscar" ) ;
  50.         panel.add ( filterText, BorderLayout.CENTER ) ;
  51.         frame.add ( panel, BorderLayout.NORTH ) ;
  52.         JButton button = new JButton ( "BUSCAR" ) ;
  53.          button.setBounds(500,100,150,20);
  54.  
  55.         button.addActionListener (
  56.                new ActionListener () {
  57.                   public void actionPerformed ( ActionEvent e ) {
  58.                     String text = filterText.getText () ;
  59.                     if ( text.length () == 0 ) {
  60.                        sorter.setRowFilter ( null ) ;
  61.                     }
  62.                     else {
  63.                        sorter.setRowFilter ( RowFilter.regexFilter ( text )) ;
  64.                     }
  65.                  }
  66.               }) ;
  67.         frame.add ( button, BorderLayout.SOUTH ) ;
  68.         frame.setSize ( 300 , 250 ) ;
  69.         frame.setVisible ( true ) ;
  70.      }
  71.  
  72.   }
  73.  
  74.  
  75.  
  76.  
y ese es mi archivo donde tengo conectada la base de datos y aqui le quiero implementar un JButton y un JTextField,con los metodos de archivo anterior,pero como NO se como armar los 2 archivos en uno solo me falta algo de logica algoritmica o matematica,pero si alguien me pudiera decir los pasos que debo hacer se lo agradecere bastante
Código
  1. import java.awt.Event.*;
  2.   import javax.swing.*;
  3.   import java.awt.*;
  4.   import javax.swing.table.*;
  5.   import java.sql.*;
  6.  
  7.    public class PruebaTabla implements ActionListener {
  8.       public static void main(String[] args)
  9.      {
  10.         NuevaVentana v=new NuevaVentana();
  11.         v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12.         v.setVisible(true);
  13.      }
  14.   }
  15.    class NuevaVentana extends JFrame{
  16.      private static final int ancho=300;
  17.      private static final int largo=300;
  18.       public NuevaVentana(){
  19.         this.setTitle("Prueba Tabla");
  20.         this.setSize(ancho,largo);
  21.         NuevoPanel p=new NuevoPanel();
  22.         add(p);
  23.  
  24.         //JButton bt= new JButton("buscar");
  25.         //bt.setBounds(300,100,150,20);
  26.        // p.add(bt);
  27.  
  28.      }
  29.   }
  30.    class NuevoPanel extends JPanel{
  31.      DefaultTableModel modelo=new DefaultTableModel();
  32.      {
  33.         modelo.addColumn("clave");
  34.         modelo.addColumn("Nombre");
  35.         modelo.addColumn("descripcion");
  36.      }
  37.      JTable tabla=new JTable(modelo);
  38.      JScrollPane scroll=new JScrollPane(tabla);
  39.       public NuevoPanel(){
  40.         this.setLayout(new BorderLayout());
  41.         add(scroll,BorderLayout.CENTER);
  42.         mostrarTabla();
  43.            JLabel label = new JLabel ( "REGISTRO" ) ;
  44.         this.add ( label, BorderLayout.WEST ) ;
  45.  
  46.       final JTextField filterText = new JTextField ( "Registro a Buscar" ) ;
  47.         this.add ( filterText, BorderLayout.NORTH  ) ;
  48.         //add ( p, BorderLayout.NORTH ) ;
  49.         JButton bt= new JButton("buscar");
  50.         //bt.setBounds(300,100,150,20);
  51.        //add(bt);
  52.      this.add (bt, BorderLayout.SOUTH ) ;
  53.      bt.addActionListener (
  54.                new ActionListener () {
  55.                   public void actionPerformed ( ActionEvent e ) {
  56.                     String text = filterText.getText () ;
  57.                     if ( text.length () == 0 ) {
  58.                        sorter.setRowFilter ( null ) ;
  59.                     }
  60.                     else {
  61.                        sorter.setRowFilter ( RowFilter.regexFilter ( text )) ;
  62.                     }
  63.                  }
  64.               }) ;
  65.  
  66.  
  67.  
  68.      }
  69.       public void mostrarTabla(){
  70.         try
  71.         {
  72.            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
  73.            Connection conexion = DriverManager.getConnection ("jdbc:mysql://localhost/almacen","root", "12345");
  74.            Statement s = conexion.createStatement();
  75.            ResultSet rs = s.executeQuery ("select * from categoria");
  76.            Object[] fila=new Object[3];
  77.            while (rs.next())
  78.            {
  79.               fila[0]=rs.getInt ("clave");
  80.               fila[1]=rs.getString ("Nombre");
  81.               fila[2]=rs.getString("descripcion");
  82.               modelo.addRow(fila);
  83.            }
  84.            conexion.close();
  85.         }
  86.             catch (Exception e)
  87.            {
  88.               e.printStackTrace();
  89.            }
  90.      }
  91.   }
  92.  
  93.  
  94.  
ojala que alguien me pueda ayudar,ya me tarde algo en implementarlo...
NOTA: todo por la che logicaaaa que me faltaa desarrollar,pero bueno!saludos!se los agradecere bastante SI ALGUIEN me ayuda bueno bye!


Título: Re: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
Publicado por: sapito169 en 21 Marzo 2011, 01:30 am
al metodo mostrar tabla ponle un parametro de tipo string
y en la consulta pon


public void mostrarTabla(String nombre){
//el mismo  codigo que tu escribiste
modelo.setRoucount(0);
 ResultSet rs = s.executeQuery ("select * from categoria where nombre like '%"+nombre+"%'");
//el resto del codigo que tu escritibste
}

public void presionCajaDeTexto(){
mostrarTabla(txtNombreCategoria.getText());
}


para que la caja de texto escuche cuando le hacen click

field.addKeyListener(new KeyAdapter() {
         @Override
         public void keyTyped(KeyEvent e) {
            presionCajaDeTexto()
         }
      });




Título: Re: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
Publicado por: hack-4-life en 21 Marzo 2011, 04:35 am
buenas gracias por tu tiempo men,bueno ya implemente tu codigo
  
El fin era para que si escribo algo en el textield me pueda filtrar los datos,pero con tu solucion es mas que suficiente,quiero hacerlo mas avanzado con un keylistener y ponerle lowerCase para mayusculas y minusculas !saludoss y gracias por tu tiempo!! saludoss :-( :-( :-(