Visualizzazione dei risultati da 1 a 4 su 4
  1. #1

    JTable con colonne contenenti JCheckBox

    Salve vorrei presentare un problema con cui lotto da giorni , sper che qualche esperto possa darmi una mano.
    Ho creato una tabella contenente 6 colonne di tipo boolean che vorrei visualizzate tramite dei checkbox ed una colonna di tipo string: in tutto 7 colonne.
    Ovviamente vorrei che quando premo su un checkbox riesca a sapere quale sia la colonna e la riga dove ho premuto ed il valore corrente del checkbox.

    Ho creato come da teoria le classi:
    class ProfileCheckBoxRenderer extends JCheckBox implements TableCellRenderer
    class ProfileCheckBoxEditor extends AbstractCellEditor implements TableCellEditor
    e le assegno ad ogni colonna.

    Sembra tutto ok in visualizzazione ma la gestione dei click e della reazione che vorrei non funziona!!
    Ripeto il problema: Vorrei che quando premo su un checkbox riesca a sapere quale sia la colonna e la riga dove ho premuto ed il valore corrente del checkbox.

    Invio il codice della classe che gestisce la tabella richiamabile con: getTable_Profile() e contenuta in SwPanelUserProfileConfiguration

    codice:
    class ProfileCheckBoxRenderer extends JCheckBox implements TableCellRenderer
       {
           public ProfileCheckBoxRenderer()
           {
               // Some look and feels might ignore this ....
        	   setHorizontalTextPosition(SwingConstants.CENTER);
    		   setHorizontalAlignment(SwingConstants.CENTER);
    		   setPreferredSize(new Dimension(90, 23));
               setRolloverEnabled(true);
           }
    
           public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
           {
               //setText(Messages.getString("Requests.ConfigurationCancelRequest.Button_Email"));
              // getModel().setRollover(hasFocus);
               return this;
           }
    
           /*
            * The following methods are overridden to be "empty" for
            * performance reasons. If you want to understand better why, please
            * read:
            * 
            * http://java.sun.com/javase/6/docs/ap...x/swing/table/
            * DefaultTableCellRenderer.html#override
            */
           public void invalidate()
           {
           }
    
           public void validate()
           {
           }
    
           public void revalidate()
           {
           }
    
           public void repaint()
           {
           }
    
           protected void firePropertyChange(String propertyName, Object oldValue, Object newValue)
           {
           }
    
           public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)
           {
           }
       }
    
       /*
        * This class extends the default editor for table and tree cells. This
        * editor is use for the button details column.
        */
       class ProfileCheckBoxEditor extends AbstractCellEditor implements TableCellEditor
       {
           private JCheckBox checkbox;
    
           public ProfileCheckBoxEditor()
           {
        	   checkbox = new InternalCheckbox();
        	   
           }
    
           public void addActionListener(ActionListener l)
           {
               // Forwards the add to the button.
        	   checkbox.addActionListener(l);
           }
    
        
    
           public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
           {
        	   
               return checkbox;
           }
    
           public Object getCellEditorValue()
           {
               return checkbox.getText();
           }
    
           private class InternalCheckbox extends JCheckBox
           {
               protected void fireActionPerformed(ActionEvent event)
               {
                   // First of all, fires all actionPerformed.
                  super.fireActionPerformed(event);
                   setHorizontalTextPosition(SwingConstants.CENTER);
        		   setHorizontalAlignment(SwingConstants.CENTER);
        		   setPreferredSize(new Dimension(90, 23));
    
                   // Then stops cell editing.
                   fireEditingStopped();
               }
           }
       }

  2. #2
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: JTable con colonne contenenti JCheckBox

    Originariamente inviato da OceanoMare1492
    Ho creato come da teoria le classi:
    class ProfileCheckBoxRenderer extends JCheckBox implements TableCellRenderer
    class ProfileCheckBoxEditor extends AbstractCellEditor implements TableCellEditor
    e le assegno ad ogni colonna.
    Non serve tutto questo. Per avere un checkbox nelle celle di una colonna è sufficiente che:
    a) Il table model "esponga" il class della colonna (da getColumnClass) come Boolean.class.
    b) Quelle celle siano editabili (isCellEditable restituisce true).
    c) Il table model "sappia" che il Object value passato a setValueAt è un Boolean (idem per getValueAt). Ovviamente anche all'esterno, chi manipola programmaticamente il table model deve "sapere" che quella colonna tratta e ha valori Boolean.

    Tutto qui.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  3. #3
    Grazie per la tua risposta celere.
    Ti invio il model ... Come dovrei modificarlo (sono un po inesperto in materia ...)

    La mia riga di tabella è la seguente:

    codice:
    class ProfileActivateRow
    	{
    	    private int ProfileId;
    	    private String ProfileName;
    	    private int UserMaxNumber;
    	    private boolean MM_Conf;
    	    private boolean MM_Monitor;
    	    private boolean MC_Conf;
    	    private boolean MC_Monitor;
    	    private boolean MI_Conf;
    	    private boolean MI_Monitor;
    	    
    	    public boolean getMM_Conf()
    	    {
    	        return MM_Conf;
    	    }
    
               public void setMM_Conf(boolean MM_Conf)
    	    {
    	        this.MM_Conf = MM_Conf;
    	    }
                   
                 .....
          }
    Mentre il Model:

    codice:
    public class ProfileActivateTableModel extends AbstractTableModel
    	{
    	    public final String[] COLUMN_NAMES = new String[] {"Profile", "MM-Conf" , "MM-Monitor", "MC-Conf", "MC-Monitor", "MI-Conf", "MI-Monitor"};
    	
    	   
    	    private Vector<ProfileActivateRow> tableData = new Vector<ProfileActivateRow>();
    	
    	    /*
    	     * getRowCount: Returns the number of rows in the model.
    	     */
    	    public int getRowCount()
    	    {
    	        return tableData.size();
    	    }
    	    
    	    
    	   
    	    public boolean isCellEditable(int rowIndex, int columnIndex)
    	    {
    	    		return true;
    	    }
    	
    	    
    	    public int getColumnCount()
    	    {
    	        return COLUMN_NAMES.length;
    	    }
    	
    	    public String getColumnName(int columnIndex)
    	    {
    	        return COLUMN_NAMES[columnIndex];
    	    }
    	
    	    
    	    public Object getValueAt(int rowIndex, int columnIndex)
    	    { 	 	
    	    	if( columnIndex == COL_PROFILE ) {
    	            return tableData.get(rowIndex).getProfileName();
    	        }
    
    	        if( columnIndex == COL_MM_CONF ) {
    	            return tableData.get(rowIndex).getMM_Conf();
    	        }
    	        
    	        if( columnIndex == COL_MM_MONITOR ) {
    	            return tableData.get(rowIndex).getMM_Monitor();
    	        }
    	        
    	        if( columnIndex == COL_MC_CONF ) {
    	            return tableData.get(rowIndex).getMC_Conf();
    	        }
    	        
    	        if( columnIndex == COL_MC_MONITOR ) {
    	            return tableData.get(rowIndex).getMC_Monitor();
    	        }
    	        
    	        if( columnIndex == COL_MI_CONF ) {
    	            return tableData.get(rowIndex).getMI_Conf();
    	        }
    	        
    	        if( columnIndex == COL_MI_MONITOR ) {
    	            return tableData.get(rowIndex).getMI_Monitor();
    	        }
    	        
    	        return null;
    	    }
    	
    	 
    	    public ProfileActivateRow getRowValue(int rowIndex)
    	    {
    	        return tableData.get(rowIndex);
    	    }
    	    
    	   
            public void removeAll()
            {
                tableData.removeAllElements();
                fireTableDataChanged();
            }
            public void removeData(int pRow)
            {
                tableData.removeElementAt(pRow);
                fireTableDataChanged();
            }
    	  
    	  
    	    
    	    public void addDataTransaction(ProfileActivateRow pOneRow)
    	    {
    	        tableData.add(pOneRow);
    	    }
    	
    	    
    	    public void commitAddDataTransaction()
    	    {
    	        fireTableDataChanged();
    	    }
    	
    	   
    	    public void removeAllElements()
    	    {
    	        synchronized (tableData) {
    	            tableData.removeAllElements();
    	        }
    	    }
    	}

  4. #4
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284
    Originariamente inviato da OceanoMare1492
    Ti invio il model ... Come dovrei modificarlo (sono un po inesperto in materia ...)
    Nel tuo table model:

    a) Devi implementare setValueAt, altrimenti i tuoi oggetti ProfileActivateRow nel tableData non vengono aggiornati. E nel setValueAt ricordati di fare alla fine un fireTableCellUpdated.
    Nota: nel getValueAt, i valori int/boolean vengono già "boxati" in automatico in Integer/Boolean, mentre nel setValueAt ricevi un Object, devi "vederlo" tu nel tipo giusto (cast) e assegnarlo in modo corretto alla proprietà.

    b) isCellEditable indica tutte celle editabili, quindi già ok.

    c) getValueAt è corretto. Potresti migliorarlo: visto che tableData.get(rowIndex) è invariante nei vari if, prendi l'oggetto solo una volta, poi magari fai uno switch per restituire la proprietà specifica della colonna.

    d) Devi implementare getColumnClass: per le proprietà int fai ritornare Integer.class, per String è String.class e per i boolean è Boolean.class (è questo che fa comparire in automatico renderer/editor già definiti dal framework con il checkbox).
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.