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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  JTable con Checkbox
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 2 [3] Ir Abajo Respuesta Imprimir
Autor Tema: JTable con Checkbox  (Leído 32,489 veces)
alzehimer_cerebral


Desconectado Desconectado

Mensajes: 513



Ver Perfil WWW
Re: JTable con Checkbox
« Respuesta #20 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.  


En línea

Servicios Informaticos Valencia - www.ag-solutions.es
Mi blog - www.alvarogarciasolano.com
Leyer


Desconectado Desconectado

Mensajes: 786


leyer@elhacker.net


Ver Perfil WWW
Re: JTable con Checkbox
« Respuesta #21 en: 10 Diciembre 2009, 18:50 pm »

en este metodo agregale algo asi.

Código
  1.     public Component getTableCellEditorComponent(JTable table, Object value,
  2.        boolean isSelected, int row, int column) {
  3.          if(isSelected){
  4.     System.out.println("---------------");
  5.        System.out.println(table.getSelectedRow());
  6.        System.out.println(value);
  7.        System.out.println("---------------");
  8.  }
  9.            return this;
  10.     }


En línea

alzehimer_cerebral


Desconectado Desconectado

Mensajes: 513



Ver Perfil WWW
Re: JTable con Checkbox
« Respuesta #22 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
En línea

Servicios Informaticos Valencia - www.ag-solutions.es
Mi blog - www.alvarogarciasolano.com
Leyer


Desconectado Desconectado

Mensajes: 786


leyer@elhacker.net


Ver Perfil WWW
Re: JTable con Checkbox
« Respuesta #23 en: 15 Diciembre 2009, 22:57 pm »

mmm que raro bueno te dejo un ejemplo  simple de como se haria


Código
  1. import java.awt.Component;
  2. import java.awt.event.MouseEvent;
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. import java.util.EventObject;
  6. import java.util.Hashtable;
  7.  
  8. import javax.swing.DefaultCellEditor;
  9. import javax.swing.JCheckBox;
  10. import javax.swing.JFrame;
  11. import javax.swing.JLabel;
  12. import javax.swing.JScrollPane;
  13. import javax.swing.JTable;
  14. import javax.swing.JTextField;
  15. import javax.swing.event.CellEditorListener;
  16. import javax.swing.table.DefaultTableCellRenderer;
  17. import javax.swing.table.DefaultTableModel;
  18. import javax.swing.table.TableCellEditor;
  19. import javax.swing.table.TableCellRenderer;
  20.  
  21. class CheckBoxRenderer extends JCheckBox implements TableCellRenderer { // Importante********
  22. private static final long serialVersionUID = 1L;
  23.  
  24.   CheckBoxRenderer() {
  25.    setHorizontalAlignment(JLabel.CENTER);
  26.  }
  27.  public Component getTableCellRendererComponent(JTable table, Object value,
  28.      boolean isSelected, boolean hasFocus, int row, int column) {
  29.    if (isSelected) {
  30.    } else {
  31.      setForeground(table.getForeground());
  32.      setBackground(table.getBackground());
  33.    }
  34.    setSelected((value != null && ((Boolean) value).booleanValue()));
  35.    return this;
  36.  }
  37. }
  38.  
  39. public class frame extends JFrame {
  40.  public frame() {
  41.    super(" Table");
  42.      public boolean isCellEditable(int row, int column) {
  43.        if (column == 0) {
  44.          return true;
  45.        }
  46.        return false;
  47.      }
  48.    };
  49.    dm.setDataVector(new Object[][] {
  50.        { "null", "String", "JLabel", "null" },
  51.        { "false", "String", "JLabel", "null" },
  52.        { new Boolean(true), "Boolean", "JCheckBox", "JCheckBox" },
  53.        { new Boolean(false), "Boolean", "JCheckBox", "JCheckBox" },
  54.        { "null", "String", "JLabel", "null" },
  55.        { "null", "String", "JLabel", "nulll" } }, new Object[] {
  56.        "Component", "Data", "Renderer", "Editor" });
  57.  
  58.    CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
  59.    EachRowRenderer rowRenderer = new EachRowRenderer();
  60.    rowRenderer.add(2, checkBoxRenderer);
  61.    rowRenderer.add(3, checkBoxRenderer);
  62.  
  63.    JCheckBox checkBox = new JCheckBox();
  64.    checkBox.setHorizontalAlignment(JLabel.CENTER);
  65.    DefaultCellEditor checkBoxEditor = new DefaultCellEditor(checkBox);
  66.    JTable table = new JTable(dm);
  67.  
  68.    EachRowEditor rowEditor = new EachRowEditor(table);
  69. //    rowEditor.setEditorAt(0, comboBoxEditor);
  70. //    rowEditor.setEditorAt(1, comboBoxEditor);
  71.    rowEditor.setEditorAt(2, checkBoxEditor);
  72.    rowEditor.setEditorAt(3, checkBoxEditor);
  73.  
  74. // end
  75.  
  76.    table.getColumn("Component").setCellRenderer(rowRenderer);
  77.    table.getColumn("Component").setCellEditor(rowEditor);
  78.  
  79.    JScrollPane scroll = new JScrollPane(table);
  80.    getContentPane().add(scroll);
  81.    setSize(400, 160);
  82.    setVisible(true);
  83.  }
  84.  
  85.  public static void main(String[] args) {
  86.    frame frame = new frame();
  87.    frame.addWindowListener(new WindowAdapter() {
  88.      public void windowClosing(WindowEvent e) {
  89.        System.exit(0);
  90.      }
  91.    });
  92.  }
  93. }
  94.  
  95. /**
  96.  * @version 1.0 11/09/98
  97.  */
  98.  
  99. class EachRowRenderer implements TableCellRenderer { // Importante********
  100.  protected Hashtable renderers;
  101.  
  102.  protected TableCellRenderer renderer, defaultRenderer;
  103.  
  104.  public EachRowRenderer() {
  105.    renderers = new Hashtable();
  106.    defaultRenderer = new DefaultTableCellRenderer();
  107.  }
  108.  
  109.  public void add(int row, TableCellRenderer renderer) {
  110.    renderers.put(new Integer(row), renderer);
  111.  }
  112.  
  113.  public Component getTableCellRendererComponent(JTable table, Object value,
  114.      boolean isSelected, boolean hasFocus, int row, int column) {
  115.  if(isSelected){
  116.     System.out.println("---------------");
  117.        System.out.println(table.getSelectedRow());
  118.        System.out.println(value);
  119.        System.out.println("---------------");
  120.  }
  121.    renderer = (TableCellRenderer) renderers.get(new Integer(row));
  122.    if (renderer == null) {
  123.      renderer = defaultRenderer;
  124.    }
  125.    return renderer.getTableCellRendererComponent(table, value, isSelected,
  126.        hasFocus, row, column);
  127.  }
  128. }
  129.  
  130. class EachRowEditor implements TableCellEditor {
  131.  protected Hashtable editors;
  132.  
  133.  protected TableCellEditor editor, defaultEditor;
  134.  
  135.  JTable table;
  136.  public EachRowEditor(JTable table) {
  137.    this.table = table;
  138.    editors = new Hashtable();
  139.    defaultEditor = new DefaultCellEditor(new JTextField());
  140.  }
  141.  public void setEditorAt(int row, TableCellEditor editor) {
  142.    editors.put(new Integer(row), editor);
  143.  }
  144.  
  145.  public Component getTableCellEditorComponent(JTable table, Object value,
  146.      boolean isSelected, int row, int column) {
  147.    //editor = (TableCellEditor)editors.get(new Integer(row));
  148.    //if (editor == null) {
  149.    //  editor = defaultEditor;
  150.    //}
  151.    return editor.getTableCellEditorComponent(table, value, isSelected,
  152.        row, column);
  153.  }
  154.  
  155.  public Object getCellEditorValue() {
  156.    return editor.getCellEditorValue();
  157.  }
  158.  
  159.  public boolean stopCellEditing() {
  160.    return editor.stopCellEditing();
  161.  }
  162.  
  163.  public void cancelCellEditing() {
  164.    editor.cancelCellEditing();
  165.  }
  166.  
  167.  public boolean isCellEditable(EventObject anEvent) {
  168.    selectEditor((MouseEvent) anEvent);
  169.    return editor.isCellEditable(anEvent);
  170.  }
  171.  
  172.  public void addCellEditorListener(CellEditorListener l) {
  173.    editor.addCellEditorListener(l);
  174.  }
  175.  
  176.  public void removeCellEditorListener(CellEditorListener l) {
  177.    editor.removeCellEditorListener(l);
  178.  }
  179.  
  180.  public boolean shouldSelectCell(EventObject anEvent) {
  181.    selectEditor((MouseEvent) anEvent);
  182.    return editor.shouldSelectCell(anEvent);
  183.  }
  184.  
  185.  protected void selectEditor(MouseEvent e) {
  186.    int row;
  187.    if (e == null) {
  188.      row = table.getSelectionModel().getAnchorSelectionIndex();
  189.    } else {
  190.      row = table.rowAtPoint(e.getPoint());
  191.    }
  192.    editor = (TableCellEditor) editors.get(new Integer(row));
  193.    if (editor == null) {
  194.      editor = defaultEditor;
  195.  
  196.  }
  197. }
  198. }
En línea

Páginas: 1 2 [3] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Ayuda con Jtable
Java
zenydark 1 3,049 Último mensaje 27 Diciembre 2010, 03:56 am
por 1mpuls0
jtable manejo
Java
geanca 3 4,177 Último mensaje 19 Febrero 2012, 16:13 pm
por jperezmonge
deshabilitar un jtable por completo
Java
josco 4 6,896 Último mensaje 4 Marzo 2012, 04:45 am
por josco
Crear JTable a mano
Java
Run.EXE 6 3,718 Último mensaje 20 Marzo 2013, 03:45 am
por Run.EXE
JTable sobre JTable
Java
CartosP 6 3,893 Último mensaje 18 Marzo 2018, 13:44 pm
por CartosP
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines