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

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


  Mostrar Mensajes
Páginas: 1 ... 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [21] 22 23 24 25 26
201  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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
  1.  
  2. package gui;
  3.  
  4. import java.awt.Component;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.FocusEvent;
  8. import java.awt.event.FocusListener;
  9. import java.util.EventObject;
  10. import java.util.LinkedList;
  11. import javax.swing.JCheckBox;
  12. import javax.swing.JTable;
  13. import javax.swing.event.CellEditorListener;
  14. import javax.swing.event.ChangeEvent;
  15. import javax.swing.table.TableCellEditor;
  16.  
  17. /**
  18.  *
  19.  * @author Gasuco
  20.  */
  21. public class TableEditor extends JCheckBox implements TableCellEditor {
  22.  
  23.  
  24.     /**
  25.       * Constructor por defecto.
  26.       */
  27.     public TableEditor()
  28.     {
  29.         // Se le ponen las opciones al JCheckBox
  30.         super.setSelected(new Boolean(false));
  31.  
  32.         // Nos apuntamos a cuando se seleccione algo, para avisar a la tabla
  33.         // de que hemos cambiado el dato.
  34.         this.addActionListener(new ActionListener() {
  35.             public void actionPerformed (ActionEvent evento)
  36.             {
  37.                 editado(true);
  38.             }
  39.         });
  40.  
  41.         // Nos apuntamos a la pérdida de foco, que quiere decir que se ha
  42.         // dejado de editar la celda, sin aceptar ninguna opción. Avisamos
  43.         // a la tabla de la cancelación de la edición.
  44.         this.addFocusListener(new FocusListener() {
  45.             public void focusGained (FocusEvent e) {;}
  46.             public void focusLost (FocusEvent e)
  47.             {
  48.                 editado (false);
  49.             }
  50.         });
  51.     }
  52.  
  53.     /** Adds a listener to the list that's notified when the editor
  54.       * stops, or cancels editing.
  55.       *
  56.       * @param l the CellEditorListener
  57.       *
  58.       */
  59.     public void addCellEditorListener(CellEditorListener l) {
  60.         // Se añade el suscriptor a la lista.
  61.         suscriptores.add (l);
  62.     }
  63.  
  64.     /** Tells the editor to cancel editing and not accept any partially
  65.       * edited value.
  66.       *
  67.       */
  68.     public void cancelCellEditing() {
  69.         // No hay que hacer nada especial.
  70.     }
  71.  
  72.     /** Returns the value contained in the editor.
  73.       * @return the value contained in the editor
  74.       *
  75.       */
  76.     public Object getCellEditorValue() {
  77.         Boolean aux= false;
  78.         // Se obtiene la opción del JCheckBox elegida y se devuelve un
  79.         // Booleano adecuado.
  80.         if (this.isSelected())
  81.         {
  82.             aux=true;
  83.         }
  84.  
  85.         else{
  86.             aux=false;
  87.         }
  88.  
  89.  
  90.         return aux;
  91.     }
  92.  
  93.     /**  Sets an initial <code>value</code> for the editor.  This will cause
  94.       *  the editor to <code>stopEditing</code> and lose any partially
  95.       *  edited value if the editor is editing when this method is called. <p>
  96.       *
  97.       *  Returns the component that should be added to the client's
  98.       *  <code>Component</code> hierarchy.  Once installed in the client's
  99.       *  hierarchy this component will then be able to draw and receive
  100.       *  user input.
  101.       *
  102.       * @param table the <code>JTable</code> that is asking the
  103.       * editor to edit; can be <code>null</code>
  104.       * @param value the value of the cell to be edited; it is
  105.       * up to the specific editor to interpret
  106.       * and draw the value.  For example, if value is
  107.       * the string "true", it could be rendered as a
  108.       * string or it could be rendered as a check
  109.       * box that is checked.  <code>null</code>
  110.       * is a valid value
  111.       * @param isSelected true if the cell is to be rendered with
  112.       * highlighting
  113.       * @param row     the row of the cell being edited
  114.       * @param column   the column of the cell being edited
  115.       * @return the component for editing
  116.       *
  117.       */
  118.     public Component getTableCellEditorComponent(JTable table, Object value,
  119.        boolean isSelected, int row, int column) {
  120.            // Devolvemos el JCheckBox del que heredamos.
  121.            return this;
  122.     }
  123.  
  124.     /** Asks the editor if it can start editing using <code>anEvent</code>.
  125.       * <code>anEvent</code> is in the invoking component coordinate system.
  126.       * The editor can not assume the Component returned by
  127.       * <code>getCellEditorComponent</code> is installed.  This method
  128.       * is intended for the use of client to avoid the cost of setting up
  129.       * and installing the editor component if editing is not possible.
  130.       * If editing can be started this method returns true.
  131.       *
  132.       * @param anEvent the event the editor should use to consider
  133.       * whether to begin editing or not
  134.       * @return true if editing can be started
  135.       * @see #shouldSelectCell
  136.       *
  137.       */
  138.     public boolean isCellEditable(EventObject anEvent) {
  139.         // La celda es editable ante cualquier evento.
  140.         return true;
  141.     }
  142.  
  143.     /** Removes a listener from the list that's notified
  144.       *
  145.       * @param l the CellEditorListener
  146.       *
  147.       */
  148.     public void removeCellEditorListener(CellEditorListener l) {
  149.         // Se elimina el suscriptor.
  150.         suscriptores.remove(l);
  151.     }
  152.  
  153.     /** Returns true if the editing cell should be selected, false otherwise.
  154.       * Typically, the return value is true, because is most cases the editing
  155.       * cell should be selected.  However, it is useful to return false to
  156.       * keep the selection from changing for some types of edits.
  157.       * eg. A table that contains a column of check boxes, the user might
  158.       * want to be able to change those checkboxes without altering the
  159.       * selection.  (See Netscape Communicator for just such an example)
  160.       * Of course, it is up to the client of the editor to use the return
  161.       * value, but it doesn't need to if it doesn't want to.
  162.       *
  163.       * @param anEvent the event the editor should use to start
  164.       * editing
  165.       * @return true if the editor would like the editing cell to be selected;
  166.       *    otherwise returns false
  167.       * @see #isCellEditable
  168.       *
  169.       */
  170.     public boolean shouldSelectCell(EventObject anEvent) {
  171.         // Indica si al editar la celda, debemos seleccionar la fila que la
  172.         // contiene.
  173.         return true;
  174.     }
  175.  
  176.     /** Tells the editor to stop editing and accept any partially edited
  177.       * value as the value of the editor.  The editor returns false if
  178.       * editing was not stopped; this is useful for editors that validate
  179.       * and can not accept invalid entries.
  180.       *
  181.       * @return true if editing was stopped; false otherwise
  182.       *
  183.       */
  184.     public boolean stopCellEditing() {
  185.         // Indica si se puede detener la edición.
  186.         return true;
  187.     }
  188.  
  189.     /**
  190.       * Si cambiado es true, se avisa a los suscriptores de que se ha terminado
  191.       * la edición. Si es false, se avisa de que se ha cancelado la edición.
  192.       */
  193.     protected void editado(boolean cambiado)
  194.     {
  195.         ChangeEvent evento = new ChangeEvent (this);
  196.         int i;
  197.         for (i=0; i<suscriptores.size(); i++)
  198.         {
  199.             CellEditorListener aux = (CellEditorListener)suscriptores.get(i);
  200.             if (cambiado)
  201.                aux.editingStopped(evento);
  202.             else
  203.                aux.editingCanceled(evento);
  204.         }
  205.     }
  206.  
  207.     /** Lista de suscriptores */
  208.     private LinkedList suscriptores = new LinkedList();
  209.  
  210.  
203  Programación / Java / Re: JTable con Checkbox en: 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
  1. public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
  2.  
  3.    JCheckBox component = new JCheckBox();
  4.  
  5.  
  6.    // This method is called when editing is completed.
  7.    // It must return the new value to be stored in the cell.
  8.    public Object getCellEditorValue() {
  9.        Boolean aux;
  10.        if(component.isSelected())
  11.            aux=true;
  12.        else
  13.            aux=false;
  14.  
  15.        return aux;
  16.  
  17.    }
  18.  
  19.     // This method is called when a cell value is edited by the user
  20.    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
  21.         // 'value' is value contained in the cell located at (rowIndex, vColIndex)
  22.  
  23.  
  24.        // isSelected true when if the cell is to be rendered with highlighting
  25.        if(isSelected){
  26.            //borrado de la fila??
  27.        }
  28.  
  29.        // Configure the component with the specified value
  30.  
  31.        if(value.equals("true")){
  32.          component.setSelected(true);
  33.  
  34.        }
  35.        else{
  36.          component.setSelected(false);
  37.  
  38.        }
  39.  
  40.  
  41.  
  42.        return component;
  43.  
  44.  
  45.    }

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  Comunicaciones / Mensajería / Re: Recuperar cuenta hotmail en: 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  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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  Programación / Java / Re: JTable con Checkbox en: 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
Páginas: 1 ... 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [21] 22 23 24 25 26
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines