Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - alzehimer_cerebral

#201
Java / Re: JTable con Checkbox
11 Diciembre 2009, 00:52 AM
L-EYER gracias por la res, lo he añadido y al clics sobre la tabla nunca entra en esa funcion...  Alguna otra idea??  Estoy atascado y no se como continuar.

Saludos.

alzehimer_cerebral
#202
Java / Re: JTable con Checkbox
10 Diciembre 2009, 18:09 PM
Haber si alguien me puede hechar una mano:

Tengo una columna en la JTable que tiene JCheckBox inicializado a false, necesito recoger el evento (cuando un usuario hace click y la pone como true), la cuestion es que no se donde se recoge el evento... Alguien me puede especificar en que metodo se recoge el cambio de la celda?? Una vez recoja el evento necesito saber en que fila de la JTable se ha realizado para asi poder proceder a eliminar dicho elemento....

Bueno al final he optado por extender JCheckBox e implementar  TableCellEditor:

Código (java) [Seleccionar]


package gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.EventObject;
import java.util.LinkedList;
import javax.swing.JCheckBox;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;

/**
*
* @author Gasuco
*/
public class TableEditor extends JCheckBox implements TableCellEditor {


     /**
      * Constructor por defecto.
      */
     public TableEditor()
     {
         // Se le ponen las opciones al JCheckBox
         super.setSelected(new Boolean(false));

         // Nos apuntamos a cuando se seleccione algo, para avisar a la tabla
         // de que hemos cambiado el dato.
         this.addActionListener(new ActionListener() {
             public void actionPerformed (ActionEvent evento)
             {
                 editado(true);
             }
         });

         // Nos apuntamos a la pérdida de foco, que quiere decir que se ha
         // dejado de editar la celda, sin aceptar ninguna opción. Avisamos
         // a la tabla de la cancelación de la edición.
         this.addFocusListener(new FocusListener() {
             public void focusGained (FocusEvent e) {;}
             public void focusLost (FocusEvent e)
             {
                 editado (false);
             }
         });
     }

     /** Adds a listener to the list that's notified when the editor
      * stops, or cancels editing.
      *
      * @param l the CellEditorListener
      *
      */
     public void addCellEditorListener(CellEditorListener l) {
         // Se añade el suscriptor a la lista.
         suscriptores.add (l);
     }

     /** Tells the editor to cancel editing and not accept any partially
      * edited value.
      *
      */
     public void cancelCellEditing() {
         // No hay que hacer nada especial.
     }

     /** Returns the value contained in the editor.
      * @return the value contained in the editor
      *
      */
     public Object getCellEditorValue() {
         Boolean aux= false;
         // Se obtiene la opción del JCheckBox elegida y se devuelve un
         // Booleano adecuado.
         if (this.isSelected())
         {
             aux=true;
         }

         else{
             aux=false;
         }


         return aux;
     }

     /**  Sets an initial <code>value</code> for the editor.  This will cause
      *  the editor to <code>stopEditing</code> and lose any partially
      *  edited value if the editor is editing when this method is called. <p>
      *
      *  Returns the component that should be added to the client's
      *  <code>Component</code> hierarchy.  Once installed in the client's
      *  hierarchy this component will then be able to draw and receive
      *  user input.
      *
      * @param table the <code>JTable</code> that is asking the
      * editor to edit; can be <code>null</code>
      * @param value the value of the cell to be edited; it is
      * up to the specific editor to interpret
      * and draw the value.  For example, if value is
      * the string "true", it could be rendered as a
      * string or it could be rendered as a check
      * box that is checked.  <code>null</code>
      * is a valid value
      * @param isSelected true if the cell is to be rendered with
      * highlighting
      * @param row      the row of the cell being edited
      * @param column  the column of the cell being edited
      * @return the component for editing
      *
      */
     public Component getTableCellEditorComponent(JTable table, Object value,
        boolean isSelected, int row, int column) {
            // Devolvemos el JCheckBox del que heredamos.
            return this;
     }

     /** Asks the editor if it can start editing using <code>anEvent</code>.
      * <code>anEvent</code> is in the invoking component coordinate system.
      * The editor can not assume the Component returned by
      * <code>getCellEditorComponent</code> is installed.  This method
      * is intended for the use of client to avoid the cost of setting up
      * and installing the editor component if editing is not possible.
      * If editing can be started this method returns true.
      *
      * @param anEvent the event the editor should use to consider
      * whether to begin editing or not
      * @return true if editing can be started
      * @see #shouldSelectCell
      *
      */
     public boolean isCellEditable(EventObject anEvent) {
         // La celda es editable ante cualquier evento.
         return true;
     }

     /** Removes a listener from the list that's notified
      *
      * @param l the CellEditorListener
      *
      */
     public void removeCellEditorListener(CellEditorListener l) {
         // Se elimina el suscriptor.
         suscriptores.remove(l);
     }

     /** Returns true if the editing cell should be selected, false otherwise.
      * Typically, the return value is true, because is most cases the editing
      * cell should be selected.  However, it is useful to return false to
      * keep the selection from changing for some types of edits.
      * eg. A table that contains a column of check boxes, the user might
      * want to be able to change those checkboxes without altering the
      * selection.  (See Netscape Communicator for just such an example)
      * Of course, it is up to the client of the editor to use the return
      * value, but it doesn't need to if it doesn't want to.
      *
      * @param anEvent the event the editor should use to start
      * editing
      * @return true if the editor would like the editing cell to be selected;
      *    otherwise returns false
      * @see #isCellEditable
      *
      */
     public boolean shouldSelectCell(EventObject anEvent) {
         // Indica si al editar la celda, debemos seleccionar la fila que la
         // contiene.
         return true;
     }

     /** Tells the editor to stop editing and accept any partially edited
      * value as the value of the editor.  The editor returns false if
      * editing was not stopped; this is useful for editors that validate
      * and can not accept invalid entries.
      *
      * @return true if editing was stopped; false otherwise
      *
      */
     public boolean stopCellEditing() {
         // Indica si se puede detener la edición.
         return true;
     }

     /**
      * Si cambiado es true, se avisa a los suscriptores de que se ha terminado
      * la edición. Si es false, se avisa de que se ha cancelado la edición.
      */
     protected void editado(boolean cambiado)
     {
         ChangeEvent evento = new ChangeEvent (this);
         int i;
         for (i=0; i<suscriptores.size(); i++)
         {
             CellEditorListener aux = (CellEditorListener)suscriptores.get(i);
             if (cambiado)
                aux.editingStopped(evento);
             else
                aux.editingCanceled(evento);
         }
     }

     /** Lista de suscriptores */
     private LinkedList suscriptores = new LinkedList();

#203
Java / Re: JTable con Checkbox
10 Diciembre 2009, 01:41 AM
Sigiendo el codigo del enlace: http://www.exampledepot.com/egs/javax.swing.table/CustEdit.html mi ejemplo...

Para mi ejemplo seria algo asi??

Código (java) [Seleccionar]
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
   
   JCheckBox component = new JCheckBox();
   
   
   // This method is called when editing is completed.
   // It must return the new value to be stored in the cell.
   public Object getCellEditorValue() {
       Boolean aux;
       if(component.isSelected())
           aux=true;
       else
           aux=false;
       
       return aux;
       
   }
   
    // This method is called when a cell value is edited by the user
   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        // 'value' is value contained in the cell located at (rowIndex, vColIndex)
     
       
       // isSelected true when if the cell is to be rendered with highlighting
       if(isSelected){
           //borrado de la fila??
       }
       
       // Configure the component with the specified value
       
       if(value.equals("true")){
         component.setSelected(true);
         
       }
       else{
         component.setSelected(false);
         
       }
   

       
       return component;
       

   }


P.D No puedo hacerlo a traves de la extension de AbstractTableModel??? A lo mejor no hace falta tocar las clases que implementan TableCellEditor y esxtienden AbstractCellEditor???  A ver si alguien me puede guiar un poco porque ando perdidooooo.

Un saludo.

alzehimer_cerebral
#204
Mensajería / Re: Recuperar cuenta hotmail
9 Diciembre 2009, 06:07 AM
La cuestion es que no me gustaria infectarme, y seguro q hay algun programa que me sirva para esto...  Ademas el Bifrost saca las de skype o Live mail??  Recuerda que no estan recordada en msn...

Saludos.

alzehimer_cerebral
#205
Java / Re: JTable con Checkbox
4 Diciembre 2009, 19:16 PM
Gracias sapito169 por la info tan detallada y los codigos tan utiles.  Se agredece este tipo de ayuda.

Un saludo.

alzehimer_cerebral
#206
Java / Re: JTable con Checkbox
30 Noviembre 2009, 18:40 PM
Gracias a todos por vuestros aportes, gracias a ello ya he avanzado bastante con mi modelo de tabla.  Ya logro cargar los datos en ella de forma correcta, pero como ya os he comentado la ultima columna es un checkbox y por lo tanto ahora tengo que recoger la accion del usuario cuando click en ella y proceder a borrar la fila correspondiente.  He consultado la API y no veo metodos ni en TableModel ni en AbstractTableModel para el borrado de una fila en concreto de la tabla, por lo tanto deduzco que la tengo que programar yo segun mi modelo, es esto asi??

Tambien necesito un poco de orientacion para saber como regoger los clicks de los usuarios sobre las checkbox, ya que no se si se hace con los listeners o con el propio checkbox??  Haber si alguien me orienta un poco para poder seguir con la JTable...

He encontrado una clase que extiende AbstractTableModel con ArrayList que suelen ser mas eficientes que los Vectores, si alguien le interesa que me lo deje saber.

Un saludo.

alzehimer_cerebral
#207
Java / Re: JTable con Checkbox
29 Noviembre 2009, 17:44 PM
Okis gracias por vuestros aportes y al final he optado por empezar de nuevo a construir mi gui todo a traves del asistente.  Lo unico que he creado un boton Open y el asistente me crea el metodo openActionPerformed(java.awt.event.ActionEvent evt), hasta aqui todo bien ya que dicho metodo me sirve para codificar la accion de pinchar sobre el boton.  Mi duda viene cuando creo un segundo boton Create y me crea 2 metodos esta vez: createActionPerformed(java.awt.event.ActionEvent evt) y createMouseClicked(java.awt.event.MouseEvent evt), mi duda es porque me crea el nuevo metodo de click del raton??  Los botones son identicos pero los metodos de las acciones son diferentes...  Que diferencia hay entre los metodos createActionPerformed y createMouseClicked??

La clase que va pintar la gui que tiene mas sentido que sea una extendida de Jpanel o de JFrame??

A ver si alguien me puede echar un cable..

Un saludo.

alzehimer_cerebral
#208
Java / Re: JTable con Checkbox
26 Noviembre 2009, 21:52 PM
Solo me sale copiar o propiedades.  Creo que tiene que ser un campo de propiedades lo que debo cambiar, sabes cual??

Saludos.

alzehimer_cerebral
#209
Java / Re: JTable con Checkbox
26 Noviembre 2009, 20:46 PM
Las 2 cosas.  Es decir creo la interfaz con el asistente y le cambio las propiedades y las funciones haciendo el codigo a mano.  Lo que pasa que probe a cambiar el modelo de la tabla con el asistente y ahora no me coje los nombres de las columnas que quiero poner a nivel de codigo a mano.

A ver si me puedes decir que leches tengo que cambiar en el asistente de GUI del netbeans en las properties de la JTable??

Saludos.

alzehimer_cerebral
#210
Java / Re: JTable con Checkbox
26 Noviembre 2009, 18:51 PM
Gracias por el link, muy bueno el ejemplo.  Habia estado googleando pero no habia encontrado nada interesante.  Ya he logrado incorporar el checkbox.

Pero me encuentro con un nuevo problema, he tocado las JTable Properties bajo la vista de "Diseño de Netbeans" y me ha cambiado los titulos de las columnas por letras (A,B,C...) y me gustaria usar los mios propios, es decir los que les paso al constructor de mi modelo de tabla.

Alguien sabe que propiedad he cambiado y lo que debo hacer para cambiar el aspecto de mi tabla??

Un saludo.

alzehimer_cerebral