elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Temas
Páginas: [1] 2 3
1  Programación / PHP / como forzar la descarga de ficheros de extensiones multiples con PHP? en: 15 Octubre 2011, 06:59 am
Buenas a todos,he estado realizando un scrip que se me ocurrio que tal vez se pueda hacer o tal vez,me paso por la mente,el scrip que quiero hacer es algo sobre descarga de archivos multiples con php o forzar la descarga de multiples extensiones esto es lo que se hace al pasarle un valor a este codigo y forza la descarga

Código
  1. <?php
  2. $enlace ="/".$id;
  3.  
  4. header ("Content-Disposition: attachment; filename=".$id." ");
  5.  
  6. header ("Content-Type: application/octet-stream");
  7.  
  8. header ("Content-Length: ".filesize($enlace));
  9.  
  10. readfile($enlace);
  11.  
  12. ?>
  13.  
  14.  
y esta demas decir que para utizarlo se le pasa la ruta dowload?id=nombrearchivo.x

pero ahora viene lo bueno,lo que yo quiero hacer es que!
lo primero seria renombrar nuestro archivo download_multiple.php y con ese archivo cuando yo lo ejecute que me descargue todo lo que se encuentra en ese directorio ya sean .png,.jpg,.zip,.rar,.pdf,.mp3,.css  ficheros de multiples extensiones por asi decirlo!

buscando me he encontrado con unos codigos que tal vez alguno de ustedes expertos en el area me pudiera sugerir este es con que estoy tratando:

Código
  1. <?php
  2. $file = $_SERVER["DOCUMENT_ROOT"].'/.../.../'.$_GET['file'];
  3.  
  4. if(!file) { // File doesn't exist, output error die('file not found'); } else {
  5.  
  6. //$file_extension = strtolower(substr(strrchr($file,"."),1));
  7. $file_extension = end(explode(".", $file));
  8.  
  9. switch( $fileExtension)
  10. {
  11. case "pdf": $ctype="application/pdf"; break;
  12. case "exe": $ctype="application/octet-stream"; break;
  13. case "zip": $ctype="application/zip"; break;
  14. case "doc": $ctype="application/msword"; break;
  15. case "xls": $ctype="application/vnd.ms-excel"; break;
  16. case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  17. case "gif": $ctype="image/gif"; break;
  18. case "png": $ctype="image/png"; break;
  19. case "jpeg":
  20. case "jpg": $ctype="image/jpg"; break;
  21. default: $ctype="application/force-download";
  22. }
  23.  
  24. nocache_headers();
  25.  
  26. // Set headers
  27. header("Pragma: public"); // required
  28. header("Expires: 0");
  29. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  30. header("Cache-Control: public"); // required for certain browsers
  31. header("Content-Description: File Transfer");
  32. header("Content-Type: $ctype");
  33. header("Content-Disposition: attachment; filename=".$file.";" );
  34. header("Content-Transfer-Encoding: binary");
  35. header("Content-Length: ".filesize($file));
  36.  
  37. readfile($file);
  38. } ?>
  39.  
  40.  
lo que entiendo por este codigo es que me descarga esos tipos de formatos de archivos,pero no se como implementarlo  tambien encontre algo asi creando un arreglo de extensiones de archivos

Código:
<?php
    $extensiones = array("PNG","zip","doc","rar","jpg");
    $f = $_GET["f"];
    if(strpos($f,"/")!==false){
        die("No puedes navegar por otros directorios");
    }
    $ftmp = explode(".",$f);
    $fExt = strtolower($ftmp[count($ftmp)-1]);

    if(!in_array($fExt,$extensiones)){
        die("<b>ERROR!</b> no es posible descargar archivos con la extensión $fExt");
    }

    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$f\"\n");
    $fp=fopen("$f", "r");
    fpassthru($fp);
?>



pero no me funciona siempre me manda aqui y no entiendo si tengo todo bien   
 die("<b>ERROR!</b> no es posible descargar archivos con la extensión $fExt");

y otra cosa que me gustaria implementar es listar todos los archivos de ese directorio para eso lo hago asi:

Código:
<?php
echo "<h3>Index</h3>\n";
echo "<table>\n";
$directorio = opendir(".");
while ($archivo = readdir($directorio))
   {
   $nombreArch = ucwords($archivo);
   $nombreArch = str_replace("..", "Atras", $nombreArch);
   echo "<tr>\n<td>\n<a href='$archivo'>\n";

   echo " border=0>\n";
   echo "<b>&nbsp;$nombreArch</b></a></td>\n";
   echo "\n</tr>\n";
   }
closedir($directorio);
echo "</table>\n";
?>


de esta manera me lista todo el directorio y de ahi partir para forzar la descarga de todos  los ficheros con extensiones que contenga la carpeta! he estado leyendo el api de php pero viene algo parecido pero no le entiendo muy bien! http://php.net/manual/en/function.readfile.php
bueno seguire buscando como implementar para descargar multiples archivos o ficheros con direntes extensiones saludos xd y de antemano gracias!
2  Programación / Java / Validar un archivo txt que solo contenga 1 y 0,para dibujar una img? en: 12 Septiembre 2011, 16:33 pm
Hola,saludos XDs!
Bueno estoy tratando de solucionar esto,se trata de poder validar un archivo de texto que contiene 1 y 0 que conforman una imagen,donde de un programa java lo mando a llamar y me pinta la imagen en un jpanel,ahora lo que yo quiero hacer es poder validarlo que si esta en el archivo 0111*+´/ cualquier otro simbolo me marque error para esto trate de hacer lo siguiente:
Código
  1.  
  2.   import java.text.*;
  3.   import java.util.*;
  4.   import java.awt.*;
  5.   import java.awt.event.*;
  6.   import java.io.*;
  7.   import java.util.StringTokenizer;
  8.   import javax.swing.*;
  9.   import javax.swing.JFileChooser;
  10.  
  11.  
  12. // Clase
  13.    class dibujo extends Frame  {
  14.      static String cad=" ";
  15.      public static String dir="";
  16.  
  17.   // Función de control de la aplicación
  18.       public static void main( String[] gll ) throws IOException{
  19.  
  20.  
  21.  
  22.         try{
  23.  
  24.  
  25.            dir= JOptionPane.showInputDialog(null,"Escribe solo el nombre del archivo a ejecutar"+" ","micky.isc");
  26.  
  27.            int a=dir.length(),b=a-4;
  28.            String sub=dir.substring(b,dir.length()),sub2=".isc";
  29.            System.out.println(sub);
  30.  
  31.            if (sub.equals(sub2)){
  32.                  //compara imagen        
  33.               FileReader ab = new FileReader(dir);
  34.               BufferedReader cd = new BufferedReader(ab);
  35.  
  36.               int numlineas = 0,total=0;
  37.               String Cadena="";
  38.  
  39.               while ((Cadena = cd.readLine())!=null) {
  40.                  numlineas++;  
  41.                  cad += Cadena+"\n";
  42.  
  43. aqui en el while no se si desde aqui lovalido ya que me lee el archivo txt...
  44.               }
  45.  
  46.            }
  47.            else
  48.            {
  49.               JOptionPane.showMessageDialog(null, "Formato no Reconocido","Error",JOptionPane.ERROR_MESSAGE);
  50.               System.exit(0);
  51.            }
  52.  
  53.         }
  54.             catch (FileNotFoundException e){
  55.               e.printStackTrace();
  56.            }
  57.             catch (IOException d){
  58.               d.printStackTrace();
  59.            }
  60.  
  61.         new dibujo();
  62.      }
  63.  
  64.       public dibujo() {
  65.  
  66.         this.setTitle( "Dibujo" );
  67.         this.setSize( 350,350 );
  68.  
  69.         this.setVisible( true );
  70.  
  71.  
  72.  
  73.         this.addWindowListener(
  74.                new WindowAdapter() {
  75.                   public void windowClosing( WindowEvent evt ) {
  76.                     System.exit( 0 );
  77.                  }
  78.               } );
  79.      }
  80.  
  81.  
  82.       public void paint(Graphics g){
  83.  
  84.         g.translate( this.getInsets().left,this.getInsets().top );
  85.  
  86.         byte[] sep = cad.getBytes();
  87.         String acep="falso";
  88.  
  89.         System.out.println ("hacker    " +sep[2]);
  90.  
  91.  
  92.         if (cad.length() >= 1000){
  93.  
  94.            int x=0,y=0;
  95.            for(int i=0; i<sep.length; i++){
  96.  
  97.  
  98.  
  99.               if (sep[i] == 48 || sep[i] == 49  || sep[i]==10  ||sep[i]==255 )
  100.               {
  101.  
  102.                  if (sep[i]==48){
  103.                     g.setColor(Color.white);
  104.                     g.fillRect( x+70,y+50,1,1);
  105.                     x=x+1;
  106.                  }
  107.  
  108.                  if (sep[i] == 49){
  109.  
  110.                     g.setColor(Color.black);
  111.                     g.fillRect( x+70,y+50,1,1 );
  112.                     x=x+1;
  113.                  }
  114.  
  115.  
  116.  
  117.  
  118.                  if (sep[i]== 10){
  119.                     y=y+1;
  120.                     x=0;
  121.                  }
  122.  
  123.  
  124.               }////
  125.               else{  
  126.      /////////////////////
  127. aqui esta mi duda le digo que si existe cualquier digito o caracter de 48=1 y 49=0
  128. me mande error pero no entra en el ciclo mi pregunta es por que!            
  129.                  if (!(sep[i]==48)&&!(sep[i] == 49)){
  130.                  System.out.println("eror"+sep[i]);
  131.                  }
  132.  
  133.  
  134.  
  135.                  System.out.println("error");
  136.               }
  137.  
  138.  
  139.  
  140.            }  
  141.  
  142.         }
  143.         else
  144.         {
  145.            JOptionPane.showMessageDialog(null,"Tu Imagen no es la Correcta","Mensage",JOptionPane.INFORMATION_MESSAGE);
  146.            System.exit(0);
  147.  
  148.         }
  149.      }
  150.   }
  151.  
  152.  
  153.  
  154.  
  155.  
  156.  

bueno espero me haya dado entender,espero me puedan ayudar...saludos...
3  Programación / Java / como limpiar datos de un jtable al cerrar una ventana que es jpanel?? en: 6 Junio 2011, 14:55 pm
hola buenas manes bueno me quede algo atoradoi y queria ver si alguien tiene una idea de como lo puedo hacerlo que necesito hacer es que cuado cierro un jpanel lo que se habia cargdo en jtable yal cerrarlo me lo vacie me lo deje igual bueno he intentado hacerlo asi
Código
  1.  
  2. bueno primero en otra clase lo declaro con esto
  3.  
  4.      private DefaultTableModel modelo_pro;
  5. y para ocuparlo lo ocupo asi de esta manera
  6.  
  7. modelo_pro = new DefaultTableModel();
  8.  
  9.  
  10.   modelo_pro.addColumn("Nombre de imagen");
  11.         modelo_pro.addColumn("Nombre de usuario");
  12.  
  13. y le paso el modelo...
  14.  
  15.         jTable2.setModel(modelo_pro);
  16. y con esto lo agrego o lo cargo al jtable
  17.  
  18.  
  19.  
  20.  
  21. public void addProceso(String app, String usuario){
  22.         Object [] fila = new Object[2];
  23.         fila[0] = app;
  24.         fila[1] = usuario;
  25.         modelo_pro.addRow ( fila ); add row para agregar
  26.      }
  27.  

pero no me la elimina bueno  habia escuchado algo asi pero no se como implementa esto
Código
  1.  
  2. por ejemplo estaba intentado que cuando se cierre la aplicacion,me limpie el jtable para esto estaba viendo la manera de hacer algo asi pero no me sale..
  3. que cuando lo cierre me limpie el jtable....
  4.  
  5.  private  class FrameListener extends WindowAdapter
  6. {
  7.        @Override
  8.    public void windowClosing ( WindowEvent e )
  9.   {
  10.  
  11.       DefaultTableModel model = (DefaultTableModel)jTable3.getModel() ;
  12.  
  13. model.setRowCount(0) ;
  14.  
  15.   }
  16. }
  17.  
bueno aqui dejo una imagen que una imagen vale mas que mil palabras que cuando cierre l jpanel me limplie el jtable  con los datos cargados de esa ventana


aver si alguien me ayuda en esa parte muchas gracias
4  Programación / Java / como pasar un resulset a un jcombobox dentro de jtable? en: 20 Mayo 2011, 18:26 pm
hola bueno,que tal, me surgio otra duda...ahora implemente lo que muchos preguntan,como tener un jcombobox a un jtable....


ahora si yo cargo los items de mi base de datos de esta manera....normalmente

Código
  1. public void cargarcombo(JComboBox jcbclave_product){
  2. try{
  3.            Class.forName (driver);
  4.  
  5.            con = DriverManager.getConnection (url,user,pass);
  6.            System.out.println ("su conexion ha sido muy exitosa"+con);
  7.            stmt = con.createStatement();
  8.  
  9.  
  10. rs = stmt.executeQuery("SELECT clave FROM productos");
  11. jcbclave_product.removeAllItems();
  12. jcbclave_product.addItem("<-Seleccionar->");
  13.  
  14. while(rs.next()==true){
  15.  
  16.    jcbclave_product.addItem(rs.getObject(1));
  17.  
  18.  
  19.  
  20.         }//fin del while
  21.         } catch (Exception e){
  22.               e.printStackTrace();
  23.  
  24.  
  25.            }//fin del try
  26.  
  27.  
  28.  
  29. }
  30.  
  31.  

y ahora mando a traer mi metodo asii

Código
  1. esto lo pongo en initscomponents
  2.    bd.cargacombo(jcbclave_product);
  3.  


ahora mi pregunta es...


como le paso los datos a un jcombobox que esta en un jtable?eso es lo que no entiendo como hacerlo...


Código
  1. yo el agrego el jcombobox en estas lineas
  2. ESTOS SON LOS datos que tiene
  3. public static final String[] DATA = { "Dato 1", "Dato 2", "Dato 3", "Dato 4" };
  4.       DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
  5.  
  6. //le digo que la COLUMNA 4 LO VA A TENER
  7.         tabla.getColumnModel().getColumn(4).setCellEditor(defaultCellEditor);
  8.  
  9.  
  10.  

ahora mi pregunta...como se lo implemento con la consulta que yo tengo vere la manera de hacerlo eso es lo que no entiendo..bueno gracias saludos
5  Programación / Java / como generar un modelo de jtable? en: 17 Mayo 2011, 05:55 am
hola manes  buenas manes...me quede atorado espero aver si alguien me puediera ayudar si no es mucha molestia.. lo que quiero hacer es si alguien me puede sugerir una manera de genrar este modelo de tabla insertando los datos de un jtable bueno este sistema lo estoy pasando a java y me pregunto como esto lo hago con java....



bueno ahora pongo la imagen que tengo hasta ahorita en java




y ahora mi codigo de la tabla que llevo hasta el momento..

Código:


public class estadodeclientes extends javax.swing.JInternalFrame {


    public estadodeclientes() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jTextField7 = new javax.swing.JTextField();
        jTextField8 = new javax.swing.JTextField();
        jTextField9 = new javax.swing.JTextField();
        jTextField10 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel11 = new javax.swing.JLabel();
        jTextField11 = new javax.swing.JTextField();

        setTitle("Estados de Cuenta");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Estados de Cuenta"));

        jLabel1.setText("Cliente:");

        jLabel2.setText("Factura:");

        jLabel3.setText("Impte venta :$");

        jLabel4.setText("Impte. Enganche:$");

        jLabel5.setText("Saldo Inicial:$");

        jLabel7.setText("Dirreccion:");

        jLabel8.setText("Colonia:");

        jLabel9.setText("Tel. Domicilio:");

        jLabel10.setText("celular:");

        jLabel6.setText("Fecha:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField9, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)))
                        .addGap(64, 64, 64)
                        .addComponent(jLabel2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel10)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addGap(36, 36, 36)
                            .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel4)
                                .addComponent(jLabel3))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(86, 86, 86)
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(58, 58, 58))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel7)
                                            .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(18, 18, 18)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel8)
                                            .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel3)
                                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(10, 10, 10)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel4)
                                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(11, 11, 11))))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel9)
                        .addComponent(jLabel10)
                        .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {new Integer(1), null, null, null, null},
                {new Integer(2), null, null, null, null},
                {new Integer(3), null, null, null, null},
                {new Integer(4), null, null, null, null},
                {new Integer(4), null, null, null, null},
                {new Integer(6), null, null, null, null},
                {new Integer(7), null, null, null, null},
                {new Integer(8), null, null, null, null},
                {new Integer(9), null, null, null, null},
                {new Integer(10), null, null, null, null},
                {new Integer(11), null, null, null, null},
                {new Integer(12), null, null, null, null}
            },
            new String [] {
                "No. Pagos", "Fecha VCTO", "Fecha de Pago:", "Importe:", "Cobrador"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Double.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel11.setText("Saldo Actual:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 561, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(63, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(366, Short.MAX_VALUE)
                .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(128, 128, 128))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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


    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    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.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField10;
    private javax.swing.JTextField jTextField11;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JTextField jTextField9;
    // End of variables declaration

}


ahora mi pregunta es como la puedo genrar automaticamente si hacerlo con un for como algo como estoo....
 y en vez de el value ponerle setvalue...alguien me puede ayudar siii? :( :( te antemano muchas gracias
Código:
   double total=0;
for (int fila=0; fila < dtm.getRowCount(); fila++) {
   total =  (double) (double) (total + (Double) dtm.getValueAt(fila, 2)); // la columna 2 es la de costo.
   this.montocompra.setText(Double.toString(total));
}


6  Programación / Java / diferentes maneras de generar un reporte en java? en: 13 Mayo 2011, 18:30 pm
bueno esto esta algo enredado,lo que quiero hacer es generar un reporte de una consulta en java,pára eso ocupo ireport y librerias jasper report...ahora aqui viene mi problema...yo creo el reporte en ireport lo diseño..lo pongoe n una ubicacion y lo mando a llamar el jrxml,me lo compila y me lo manda en pantalla.....pero estaba pensando..si alguien de ustedes me podria decir la manera en que se puede ser automaticamente...

Oseaa tomar la tabla que esta activa con los registros y mandar el reporte asi automatico como hacen los sistemas de oxxo del walrtmart etc...

bueno con este codigo automaticamente me manda a imprimir......esto seria una
Código
  1. private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {                                            
  2.         try {
  3.            //Mensaje de encabezado
  4.            MessageFormat headerFormat = new MessageFormat("Tutorial Imprimir JTables");
  5.            //Mensaje en el pie de pagina
  6.            MessageFormat footerFormat = new MessageFormat("ContreSpace");
  7.            //Imprimir JTable
  8.            tabla.print(JTable.PrintMode.NORMAL, headerFormat, footerFormat);
  9.        } catch (PrinterException ex) {
  10.            Logger.getLogger(frmImprimir_JTable.class.getName()).log(Level.SEVERE, null, ex);
  11.        }
  12.    }                                        
  13.  
  14.  
  15.  

ahoraa me pregunto si tal si le paso un query y de ese query me genera el reporte,perooo el reporte lo tengo que diseñar...con ireport...sigo buscando de como hacer esto pasando un query y que de ahi me genere el reporte..algo como esto
Código
  1. package imprimir_jtable;
  2.  
  3. import net.sf.jasperreports.engine.*;
  4. import net.sf.jasperreports.engine.export.*;
  5. import net.sf.jasperreports.engine.util.*;
  6. import net.sf.jasperreports.view.*;
  7. import java.sql.*;
  8.  
  9. import java.io.*;
  10. import java.util.*;
  11.  
  12. public class Main {
  13.  
  14.    public Main() {
  15.    }
  16.  
  17.    public static void main(String[] args) {
  18.        // TODO code application logic here
  19.  
  20.    try
  21.    {
  22.  
  23.        //Ruta de Archivo Jasper
  24.        String fileName="C:\\Users\\Hacker\\Desktop\\rep_cli.jasper";
  25.        //Ruta de archivo pdf de destino
  26.        String destFileNamePdf="C:\\Users\\Hacker\\Desktop\\rep_cli.pdf";
  27.        //Ruta de archivo xls de destino
  28.        String destFileNameXls="C:\\Users\\Hacker\\Desktop\\rep_cli.xls";
  29.  
  30.        //Pasamos parametros al reporte Jasper.
  31.        Map parameters = new HashMap();
  32.            Object put = parameters.put("sql_query",new String("select * from categorias"));
  33.  
  34.  
  35.        //Preparacion del reporte (en esta etapa se inserta el valor del query en el reporte).
  36.        JasperPrint jasperPrint=JasperFillManager.fillReport(fileName, (Map) put,getConnection());
  37.  
  38.        //Creación del PDF
  39.        JasperExportManager.exportReportToPdfFile(jasperPrint,destFileNamePdf);
  40.  
  41.        //Creación del XLS
  42.        JRXlsExporter exporter = new JRXlsExporter();
  43.        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
  44.        exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFileNameXls);
  45.        exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
  46.        exporter.exportReport();
  47.  
  48.        System.exit(0);
  49.     }
  50.     catch (Exception e)
  51.     {
  52.            System.out.println(e.getMessage());
  53.     }
  54.    }
  55.  
  56.    /**Metodo para crear la conexion a DB*/
  57.    private static Connection getConnection() throws ClassNotFoundException, SQLException {
  58.        //Configuración de la conexión.
  59.        String driver = "com.mysql.jdbc.Driver";
  60.        String connectString = "jdbc:mysql://127.0.0.1:3306/almacen";
  61.        String user = "root";
  62.        String password = "12345";
  63.  
  64.        Class.forName(driver);
  65.        Connection conn = DriverManager.getConnection(connectString, user, password);
  66.  
  67.        //Retornamos la conexión establecida.
  68.    return conn;
  69. }
  70.  
  71. }
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  


esta otra manera encontre donde se le pasan las columnas y las filas pero ahi ya estan declaradas como seria para pasarle un query me lo genere de ese resultado....aqui ocupan la libreria  libreria itext
Código
  1.  
  2.  
  3. package imprimir_jtable;
  4.  
  5. import java.awt.BorderLayout;
  6.  
  7. import java.awt.Graphics2D;
  8.  
  9. import java.awt.Shape;
  10.  
  11. import java.awt.event.ActionEvent;
  12.  
  13. import java.awt.event.ActionListener;
  14.  
  15. import java.awt.event.WindowAdapter;
  16.  
  17. import java.awt.event.WindowEvent;
  18.  
  19. import java.io.FileOutputStream;
  20.  
  21. import java.io.IOException;
  22.  
  23. import javax.swing.JButton;
  24.  
  25. import javax.swing.JFrame;
  26.  
  27. import javax.swing.JPanel;
  28.  
  29. import javax.swing.JTable;
  30.  
  31. import javax.swing.JToolBar;
  32.  
  33. import com.lowagie.text.Document;
  34.  
  35. import com.lowagie.text.DocumentException;
  36.  
  37. import com.lowagie.text.PageSize;
  38.  
  39. import com.lowagie.text.pdf.PdfContentByte;
  40.  
  41. import com.lowagie.text.pdf.PdfWriter;
  42.  
  43.  
  44. public class JTable2Pdf extends JFrame {
  45.  
  46.  
  47. private JTable table;
  48.  
  49.  
  50. public JTable2Pdf() {
  51.  
  52. getContentPane().setLayout(new BorderLayout());
  53.  
  54. setTitle("JTable test");
  55.  
  56. createToolbar();
  57.  
  58. createTable();
  59.  
  60. addWindowListener(new WindowAdapter() {
  61.  
  62. public void windowClosing(WindowEvent e)
  63.  
  64. {System.exit(0);}
  65.  
  66. });
  67.  
  68. }
  69.  
  70.  
  71.  
  72. private void createTable() {
  73.  
  74. Object[][] data ={
  75.  
  76. {"Mary", "Campione", "Snowboarding", new
  77.  
  78. Integer(5), new Boolean(false)},
  79.  
  80. {"Alison", "Huml", "Rowing", new
  81.  
  82. Integer(3), new Boolean(true)},
  83.  
  84. {"Kathy", "Walrath", "Chasing toddlers",
  85.  
  86. new Integer(2), new Boolean(false)},
  87.  
  88. {"Mark", "Andrews", "Speed reading", new
  89.  
  90. Integer(20), new Boolean(true)},
  91.  
  92. {"Angela", "Lih", "Teaching high school", new Integer(4), new Boolean(false)}
  93.  
  94. };
  95.  
  96. String[] columnNames =
  97.  
  98. {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
  99.  
  100. table = new JTable(data, columnNames);
  101.  
  102. // Use a panel to contains the table and add it the frame
  103.  
  104. JPanel tPanel = new JPanel(new BorderLayout());
  105.  
  106. tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
  107.  
  108. tPanel.add(table, BorderLayout.CENTER);
  109.  
  110. getContentPane().add(tPanel, BorderLayout.CENTER);
  111.  
  112. }
  113.  
  114.  
  115. private void createToolbar() {
  116.  
  117. JToolBar tb = new JToolBar();
  118.  
  119. JButton printBtn = new JButton("Print");
  120.  
  121. printBtn.addActionListener(new ActionListener() {
  122.  
  123. public void actionPerformed(ActionEvent e) {
  124.  
  125. print();
  126.  
  127. }
  128.  
  129. });
  130.  
  131. JButton exitBtn = new JButton("Exit");
  132.  
  133. exitBtn.addActionListener(new ActionListener() {
  134.  
  135. public void actionPerformed(ActionEvent e) {
  136.  
  137. exit();
  138.  
  139. }
  140.  
  141. });
  142.  
  143. tb.add(printBtn);
  144.  
  145. tb.add(exitBtn);
  146.  
  147. getContentPane().add(tb, BorderLayout.NORTH);
  148.  
  149. }
  150.  
  151. /////////ojoo aqui es para imprimir el pdf
  152. private void print() {
  153.  
  154. Document document = new Document(PageSize.A4.rotate());
  155.  
  156. try {
  157.  
  158. PdfWriter writer =
  159.  
  160. PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\Hacker\\Desktop\\myy_jtable_fonts.pdf"));
  161.  
  162. document.open();
  163.  
  164. PdfContentByte cb = writer.getDirectContent();
  165.  
  166. // Create the graphics as shapes
  167.  
  168. cb.saveState();
  169.  
  170. Graphics2D g2 = cb.createGraphicsShapes(500, 500);
  171.  
  172. // Print the table to the graphics
  173.  
  174. Shape oldClip = g2.getClip();
  175.  
  176. g2.clipRect(0, 0, 500, 500);
  177.  
  178. table.print(g2);
  179.  
  180. g2.setClip(oldClip);
  181.  
  182. g2.dispose();
  183.  
  184. cb.restoreState();
  185.  
  186. document.newPage();
  187.  
  188. // Create the graphics with pdf fonts
  189.  
  190. cb.saveState();
  191.  
  192. g2 = cb.createGraphics(500, 500);
  193.  
  194. // Print the table to the graphics
  195.  
  196. oldClip = g2.getClip();
  197.  
  198. g2.clipRect(0, 0, 500, 500);
  199.  
  200. table.print(g2);
  201.  
  202. g2.setClip(oldClip);
  203.  
  204. g2.dispose();
  205.  
  206. cb.restoreState();
  207.  
  208. } catch (Exception e) {
  209.  
  210. e.printStackTrace();
  211.  
  212. System.err.println(e.getMessage());
  213.  
  214. }
  215.  
  216. document.close();
  217.  
  218. }
  219.  
  220. /**
  221.  
  222. * Exit app
  223.  
  224. */
  225.  
  226. private void exit() {
  227.  
  228. System.exit(0);
  229.  
  230. }
  231.  
  232.  
  233. public static void main(String[] args) {
  234.  
  235. JTable2Pdf frame = new JTable2Pdf();
  236.  
  237. frame.pack();
  238.  
  239. frame.setVisible(true);
  240.  
  241. frame.print();
  242.  
  243. frame.exit();
  244.  
  245. }
  246.  
  247. }v
  248.  
  249.  

y esto me da como resultado esto...

no se si ustedes me podria ayudar o dar alguna sugerenciaa  de como han ustedes trabajado con esto y solucionado,si no es mucha molestiaa...de antemano muchas gracias saludos...maness.... seguire buscando en el sen sei google e ir implementando aver si me sale algo decente .. :-\ :-\
7  Programación / Java / como controlar campo autoincrement en mysql y java? en: 12 Mayo 2011, 02:39 am
hola buenas men..bueno mi duda es si alguien ha trabajado con un campo increment lo unico que quiero es saber tengo un campo factura en donde realizo ventas y en las ventas el sistema asigna un contador... ahora eso es lo que quiero incrementar como esta imagen...


si de dan cuenta saco la factura con esto

Código:

public void cargarnum_factura(JTextField jtxt_factura){
 try{
            Class.forName (driver);
con = DriverManager.getConnection (url,user,pass);
            System.out.println ("su conexion ha sido muy exitosa"+con);
rs = stmt.executeQuery("SELECT factura FROM ventas ");
//reiniciar contador a cero ALTER TABLE nombre_tabla AUTO_INCREMENT= 1
                ResultSetMetaData RSMD = rs.getMetaData();
                int ColumnCount = RSMD.getColumnCount();
                Object[] Resultados = new Object[ColumnCount];
                while(rs.next()){
                    for(int x=1;x<ColumnCount;x++){
                        Resultados[x] = rs.getObject(x+1); aqui le sumo uno pero como la imagen de igual manera me aparece 2 y tiene que ser 3 este metodo lo pongo en item mouseclicked para que lo haga gracias
                    }
                }
//aqui lo mando ami jtexfield
                jtxt_factura.setText(Resultados[0].toString());

            } catch (Exception ex) {

            }

}

bueno espero si alguien me pudiese ayudar no os quitara mucho tiempo de vos saludos
8  Programación / Java / como calcular el costo e importe de un producto en java y mysql? en: 4 Mayo 2011, 02:01 am
buenas que tal a todos,bueno tal vez mi pregunta este un poco enredada..pero me surgio una duda..tengo una aplicacion llamada ventas y en la cual tengo yn jcombobox y ahi cargo las claves de los productos...ahora mi duda es como le puedo hacer que dependiendo de la clave del producto,me calcule el costo y el importe total.. tomando en cuenta que esa clave del producto tien un nombre y ese nombre de ese producto puede contener iva o no puede contener iva..pero como le hago para que m me lo calcule automaticamente..mi duda es como le hago que dependiendo de la clave que se escoja me calcule l importe estaba pensando en esto

si hago un select iva from producto where clave=jcombobox.getselecteditem() y esa consulta la guardo en una variable o como le puedo hacer..para que nos entendamos aqui dejo una imagenn saludos...

bueno si de dan cuenta aqui agrego la clave al producto y su costoo y el ivaa


ahora aqui en esta imagen despliego la clave que claro la clave ya contien un costo y ese producto puede contener iva o no puede contener iva


entonces como calculo que depndiendo del producto que escoga y la cantidad que quieren comprar calcule el costo y el importe total no se si me pudiera dar alguna sugerencia de antemano muchas gracias saludos...
9  Programación / Java / filtrar Texto en un JTable conectado a un BD con un JButton y un JTextField? 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!
10  Programación / Java / Como Realizar un Buscador en Java y MySql? en: 12 Marzo 2011, 22:48 pm
Buenas saludos a todos,bueno mi problema es que intento realizar un buscador en java,pero lo quiero es que cuando vaya escribiendo en el JTextField();y me vayan apareciendo los posibles resultados,lo estoy implementando con esto:
Código
  1.   public String[] buscarpersona (int id){
  2.  
  3.  
  4.         try
  5.         {
  6.            Class.forName (driver);
  7.  
  8.            con = DriverManager.getConnection (url + db,user,pass);
  9.            System.out.println ("su conexion ha sido muy exitosa");
  10.            stmt = con.createStatement();
  11.            rs=stmt.executeQuery("SELECT * FROM personas WHERE personaid='" +id+"'");
  12.            ResultSetMetaData rsmd=rs.getMetaData();
  13.            datos=new String[rsmd.getColumnCount()];
  14.            int cont2=1;
  15.         //ciclo de llenado de resultset al arreglo para poder mandarlo al programa
  16.         //arreglo-->0
  17.         //resultset-->1
  18.            while(rs.next()){
  19.               for(int cont=0;cont<rsmd.getColumnCount();cont++){
  20.                  datos[cont]=rs.getString(cont2);
  21.                  cont2++;
  22.  
  23.               }
  24.            }
  25.            stmt.close();
  26.            con.close();
  27.            return datos;
  28.  
  29.         }
  30.             catch (Exception e){
  31.               e.printStackTrace();
  32.               System.err.println ( e.getMessage ());
  33.  
  34.  
  35.  
  36.  
  37.  
  38.               return datos;
  39.  
  40.  
  41.  
  42.  
  43.  
  44.            }
  45.      }
  46.  
  47.  

y esto es lo que tengo en java:
Código
  1.  
  2. private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt){
  3. String datos[];
  4. try{
  5. int id=Integer.parseInt(txtReg.getText());
  6. datos=bd.BuscarPersona(id);
  7. if(datos!=null){
  8. //datos[0] corresponde al id
  9. txtNombre.setText(datos[1]);
  10. txtDomicilio.setText(datos[2]);
  11. txtMail.setText(datos[3]);
  12. txtCiudad.setText(datos[4]);
  13. }
  14. }catch(Exception e){
  15. JOptionPane.showMessageDialog(this,"debe escribir un numero en el campo de registro","aviso",JOptionPane.ERROR_MESSAGE);
  16. txtReg.grabFocus();
  17. txtReg.selectAll();
  18. }
  19. }
  20.  
  21.  
aver si alguien me puede recomendar algo,estaba buscando sobre keylistener,no se si alguno de ustedes han hecho algo parecido,saludos y gracias de antemano xauz...
Páginas: [1] 2 3
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines