elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.
 
Inicio Ayuda Buscar Ingresar Registrarse
28 Mayo 2012, 02:00  


Tema destacado: Entra al canal IRC oficial de #elhacker.net

+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java (Moderadores: Debci, Leyer)
| | | |-+  filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?  (Leído 1,971 veces)
hack-4-life

Desconectado Desconectado

Mensajes: 52



Ver Perfil WWW
filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
« en: 20 Marzo 2011, 00:14 »

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
 import java.awt.BorderLayout;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
 
  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;
  import javax.swing.JTable;
  import javax.swing.JTextField;
  import javax.swing.RowFilter;
  import javax.swing.table.DefaultTableModel;
  import javax.swing.table.TableModel;
  import javax.swing.table.TableRowSorter;
 
   public class RegexTable {
      public static void main ( String args []) {
        JFrame frame = new JFrame ( "BUSCAR EN UN JTABLE" ) ;
        frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ;
        Object rows [][] = { { "A" , "About" , 44.36 } , { "B" , "Boy" , 44.84 } , { "C" , "Cat" , 463.63 } ,
              { "D" , "Day" , 27.14 } , { "E" , "Eat" , 44.57 } , { "F" , "Fail" , 23.15 } ,
              { "G" , "Good" , 4.40 } , { "H" , "Hot" , 24.96 } , { "I" , "Ivey" , 5.45 } ,
              { "J" , "Jack" , 49.54 } , { "K" , "Kids" , 280.00 } } ;
        String columns [] = { "NOMBRE" , "DESCRIPCION" , "PRECIO" } ;
        TableModel model =
            new DefaultTableModel ( rows, columns ) {
               public Class getColumnClass ( int column ) {
                 Class returnValue;
                 if (( column >= 0 ) && ( column < getColumnCount ())) {
                    returnValue = getValueAt ( 0 , column ) .getClass () ;
                 }
                 else {
                    returnValue = Object. class ;
                 }
                 return returnValue;
              }
           } ;
 
        final JTable table = new JTable ( model ) ;
        final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel> ( model ) ;
        table.setRowSorter ( sorter ) ;
        JScrollPane pane = new JScrollPane ( table ) ;
        frame.add ( pane, BorderLayout.CENTER ) ;
 
        JPanel panel = new JPanel ( new BorderLayout ()) ;
        JLabel label = new JLabel ( "REGISTRO" ) ;
        panel.add ( label, BorderLayout.WEST ) ;
        final JTextField filterText = new JTextField ( "Registro a Buscar" ) ;
        panel.add ( filterText, BorderLayout.CENTER ) ;
        frame.add ( panel, BorderLayout.NORTH ) ;
        JButton button = new JButton ( "BUSCAR" ) ;
         button.setBounds(500,100,150,20);
 
        button.addActionListener (
               new ActionListener () {
                  public void actionPerformed ( ActionEvent e ) {
                    String text = filterText.getText () ;
                    if ( text.length () == 0 ) {
                       sorter.setRowFilter ( null ) ;
                    }
                    else {
                       sorter.setRowFilter ( RowFilter.regexFilter ( text )) ;
                    }
                 }
              }) ;
        frame.add ( button, BorderLayout.SOUTH ) ;
        frame.setSize ( 300 , 250 ) ;
        frame.setVisible ( true ) ;
     }
 
  }
 
 
 
 
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
 import java.awt.Event.*;
  import javax.swing.*;
  import java.awt.*;
  import javax.swing.table.*;
  import java.sql.*;
 
   public class PruebaTabla implements ActionListener {
      public static void main(String[] args)
     {
        NuevaVentana v=new NuevaVentana();
        v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        v.setVisible(true);
     }
  }
   class NuevaVentana extends JFrame{
     private static final int ancho=300;
     private static final int largo=300;
      public NuevaVentana(){
        this.setTitle("Prueba Tabla");
        this.setSize(ancho,largo);
        NuevoPanel p=new NuevoPanel();
        add(p);
 
        //JButton bt= new JButton("buscar");
        //bt.setBounds(300,100,150,20);
       // p.add(bt);
 
     }
  }
   class NuevoPanel extends JPanel{
     DefaultTableModel modelo=new DefaultTableModel();
     {
        modelo.addColumn("clave");
        modelo.addColumn("Nombre");
        modelo.addColumn("descripcion");
     }
     JTable tabla=new JTable(modelo);
     JScrollPane scroll=new JScrollPane(tabla);
      public NuevoPanel(){
        this.setLayout(new BorderLayout());
        add(scroll,BorderLayout.CENTER);
        mostrarTabla();
           JLabel label = new JLabel ( "REGISTRO" ) ;
        this.add ( label, BorderLayout.WEST ) ;
 
      final JTextField filterText = new JTextField ( "Registro a Buscar" ) ;
        this.add ( filterText, BorderLayout.NORTH  ) ;
        //add ( p, BorderLayout.NORTH ) ;
        JButton bt= new JButton("buscar");
        //bt.setBounds(300,100,150,20);
       //add(bt);
     this.add (bt, BorderLayout.SOUTH ) ;
     bt.addActionListener (
               new ActionListener () {
                  public void actionPerformed ( ActionEvent e ) {
                    String text = filterText.getText () ;
                    if ( text.length () == 0 ) {
                       sorter.setRowFilter ( null ) ;
                    }
                    else {
                       sorter.setRowFilter ( RowFilter.regexFilter ( text )) ;
                    }
                 }
              }) ;
 
 
 
     }
      public void mostrarTabla(){
        try
        {
           DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
           Connection conexion = DriverManager.getConnection ("jdbc:mysql://localhost/almacen","root", "12345");
           Statement s = conexion.createStatement();
           ResultSet rs = s.executeQuery ("select * from categoria");
           Object[] fila=new Object[3];
           while (rs.next())
           {
              fila[0]=rs.getInt ("clave");
              fila[1]=rs.getString ("Nombre");
              fila[2]=rs.getString("descripcion");
              modelo.addRow(fila);
           }
           conexion.close();
        }
            catch (Exception e)
           {
              e.printStackTrace();
           }
     }
  }
 
 
 
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!


En línea

""DE QUE SIRVE EL CONOCIMIENTO SI SE PRIVA DE SU DISTRIBUCION"
sapito169


Desconectado Desconectado

Mensajes: 421



Ver Perfil
Re: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
« Respuesta #1 en: 21 Marzo 2011, 01:30 »

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()
         }
      });




En línea

hack-4-life

Desconectado Desconectado

Mensajes: 52



Ver Perfil WWW
Re: filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField?
« Respuesta #2 en: 21 Marzo 2011, 04:35 »

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 :-( :-( :-(
« Última modificación: 22 Marzo 2011, 20:36 por hack-4-life » En línea

""DE QUE SIRVE EL CONOCIMIENTO SI SE PRIVA DE SU DISTRIBUCION"
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
como filtrar caracteres en un texto (snippet)
Programación Visual Basic
el_c0c0 5 884 Último mensaje 5 Noviembre 2008, 14:40
por Karcrack
JTable tamaño de celdas ajustable y mostrar texto completo
Java
marvic 1 6,705 Último mensaje 12 Abril 2009, 19:57
por marvic
Obtencion string de un JTextField
Java
Eage 2 4,516 Último mensaje 26 Julio 2009, 19:53
por DonVidela
[Solucionado] [Ayuda] Filtrar texto
Programación Visual Basic
agus0 9 1,555 Último mensaje 9 Noviembre 2009, 09:33
por xkiz ™
Filtrar resultados de JTable que no sea Case Sensitive (ni mayus, ni minus)
Java
Aikanáro Anário 5 769 Último mensaje 28 Noviembre 2011, 18:32
por ZedGe
Powered by SMF 1.1.16 | SMF © 2006-2008, Simple Machines