IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

Problème avec l'insertion d'un JCheckBox dans un tableau


Sujet :

Composants Java

  1. #1
    Membre éclairé Avatar de aljessy
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2010
    Messages
    319
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2010
    Messages : 319
    Par défaut Problème avec l'insertion d'un JCheckBox dans un tableau
    Bonjour j'ai crée mon propre TableModel. Maintenant je suis bloqué lorsque je veux ajouter un checkbox dans mon tableau. J'ai beau override getColumModel(), rien n'est fait. Mon checkbox n'apparait toujours pas. Voici le code que j'utilise :

    //Mon TableModel:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
     
    /**
     * 
     */
    package com.mbassi.curve.gui.model;
     
    import java.util.List;
     
    import javax.swing.table.AbstractTableModel;
     
    import org.apache.log4j.Logger;
     
    /**
     * @author BODUSMAN
     *
     */
    public class CurveJTableModel extends AbstractTableModel{
     
    	/**
             * 
             */
    	protected static final long serialVersionUID = 1L;
     
    	protected boolean DEBUG;
    	protected Logger log = Logger.getLogger(CurveJTableModel.class);
     
        public CurveJTableModel(){
     
        }
     
        public CurveJTableModel(String [] columnNames, Object[] columnTypes, Object[][] tableData){
     
        	setColumnNames(columnNames);
        	this.longValues = columnTypes;
        	if(tableData != null)
        		this.tableData = tableData;
        }
     
        /**
         * Tableau de Boolean indicant si une colonne est editable ou pas 
         */
        protected boolean[] editableColumns = new boolean[]{false};
     
        /**
         * Tableau contenant les noms des colonnes
         */
        protected String[] columnNames = new String[]{};
     
        protected int columnCount = 0;
     
        /**
         * Tableau contenant les données d'un JTable
         */
        protected Object[][] tableData = new Object[0][columnNames.length];
     
        /**
         * Tableau permettant de recueillir les types de donnée des colonnes
         */
        protected Object[] longValues = {};
     
        /**
         * Méthode retournant le nombre de colonnes d'un <code>JTable</code>
         * @return
         */
        @Override
        public int getColumnCount() {
            return columnCount;
        }
     
        /**
         * Méthode retournant le nombre de lignes d'un <code>JTable</code>
         * @return
         */
        @Override
        public int getRowCount() {
            return tableData == null ? 0 : tableData.length;
        }
     
        @Override
        public String getColumnName(int col) {
        	//
            return columnNames[col];
        }
     
        @Override
        public Object getValueAt(int row, int col) {
        	try {
        		return tableData[row][col];
    		} catch ( java.lang.ArrayIndexOutOfBoundsException e) {
    			log.warn(" Error in "+CurveJTableModel.class+".getValueAt(int row, int col) - Index invalide : " + e.getStackTrace());
    			return null;
    		} catch ( Exception e) {
    			log.warn("Error in "+CurveJTableModel.class+".getValueAt(int row, int col) : " + e.getStackTrace());
    			return null;
    		}
     
        }
     
        @SuppressWarnings("unchecked")
    	@Override
        public Class getColumnClass(int c) {
        	try {
                return getRowCount() == 0 || getValueAt(0, c) == null ? String.class : getValueAt(0, c).getClass();
    		} catch (ArrayIndexOutOfBoundsException e) {
    			log.warn(" Error in "+CurveJTableModel.class+".getColumnClass(int col) - Index invalide : " + e.getStackTrace());
    			return null;
    		} catch ( Exception e) {
    			log.warn("Error in "+CurveJTableModel.class+".getColumnClass(int col) : " + e.getStackTrace());
    			return null;
    		}
     
        }
     
     
        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        @Override
        public boolean isCellEditable(int row, int col) {
            //Note that the tableData/cell address is constant,
            //no matter where the cell appears onscreen.
        	try{
        		return editableColumns[col];    
        	}catch(Exception ex){
        		log.warn("Exception in " + this.getClass() + ".isCellEditable() : " + ex.getStackTrace());
        		return false;
        	}
     
        }
     
        /*
         * Don't need to implement this method unless your table's
         * tableData can change.
         */
        @Override
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
    //            System.out.println("Setting value at " + row + "," + col
    //                               + " to " + value
    //                               + " (an instance of "
    //                               + value.getClass() + ")");
            }
     
            tableData[row][col] = value;
            fireTableCellUpdated(row, col);
     
            if (DEBUG) {
    //            System.out.println("New value of tableData :");
    //            printDebugData();
            }
        }
     
    //    private void printDebugData() {
    //        int numRows = getRowCount();
    //        int numCols = getColumnCount();
    //
    //        for (int i=0; i < numRows; i++) {
    //            System.out.print("    row " + i + ":");
    //            for (int j=0; j < numCols; j++) {
    //                System.out.print("  " + tableData[i][j]);
    //            }
    //            System.out.println();
    //        }
    //        System.out.println("--------------------------");
    //    }
     
     
        /**
         * Méthode remplissant les données du tableau (la variable data du tableau)
         * 
         * @param elementList Liste des éléments à insérer dans le tableau
         */
        public void fillTable(List <Object> elementList){
        	/*
        	 * A Implémenter par le développeur
        	 */
        }
     
    	/**
             * @return the tableData
             */
    	public Object[][] getTableData() {
    		return tableData;
    	}
     
     
    	/**
             * @param tableData the tableData to set
             */
    	public void setTableData(Object[][] tableData) {
    		this.tableData = tableData;
    	}
     
    	/**
             * @return the columnNames
             */
    	public String[] getColumnNames() {
    		return columnNames;
    	}
     
    	/**
             * @return the longValues
             */
    	public Object[] getLongValues() {
    		return longValues;
    	}
     
    	/**
             * @param columnNames the columnNames to set
             */
    	public void setColumnNames(String[] columnNames) {
    		this.columnNames = columnNames;
    		int length = columnCount = columnNames == null ? 0 : columnNames.length;
     
    		editableColumns = new boolean[length];
    		for(int i = 0; i < length; i++){
    			editableColumns[i] = false;
    		}
    	}
     
    	/**
             * @param longValues the longValues to set
             */
    	public void setLongValues(Object[] longValues) {
    		this.longValues = longValues;
    	}
     
    	/**
             * @return the editableColumns
             */
    	public boolean[] getEditableColumns() {
    		return editableColumns;
    	}
     
    	/**
             * @param editableColumns the editableColumns to set
             */
    	public void setEditableColumns(boolean[] editableColumns) {
    		this.editableColumns = editableColumns;
    	}
     
    	public void setColumnCount(int columnCount) {
    		this.columnCount = columnCount;
    	}
     
    }
    Voici l'utisation que j'en fais pour essayé d'afficher mon checkbox:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
     
    private void resetClassePeriodeJTable(CurveJTable table, Periode p, Double pourcentage) {
     
        	final Periode periode = p;
        	final Double pourcent = pourcentage;
     
        	classePeriodeModel = new CurveJTableModel(){
    			private static final long serialVersionUID = -946584942570080930L;
     
    			@Override
    		    public Class getColumnClass(int c) {
    		    	try {
    		    		if(c == 0)
    		    			return Boolean.class;
    		    		else
    		    			return getRowCount() == 0 || getValueAt(0, c) == null ? String.class : getValueAt(0, c).getClass();
    				} catch (ArrayIndexOutOfBoundsException e) {
    					log.warn(" Error in "+CurveJTableModel.class+".getColumnClass(int col) - Index invalide : " + e.getStackTrace());
    					return null;
    				} catch ( Exception e) {
    					log.warn("Error in "+CurveJTableModel.class+".getColumnClass(int col) : " + e.getStackTrace());
    					return null;
    				}
     
    		    }
     
    			/**
                             * Méthode remplissant les données du tableau (la variable data du tableau)
                             * 
                             * @param elementList Liste des éléments à insérer dans le tableau
                             */
    			@Override
    			public void fillTable(List <Object> periodeList){
    				int length = (periodeList == null ? 0 : periodeList.size());
    				tableData = new Object[length][columnNames.length];
    				for(int i = 0; i < length; i++){
    					tableData[i][0] = false;
    					tableData[i][1] = null;
    					tableData[i][2] = null;
    					tableData[i][3] = null;
    					tableData[i][4] = null;
     
    					if((periodeList.get(i) != null) && periodeList.get(i) instanceof Classe){
    						Classe current = (Classe) periodeList.get(i);
    						tableData[i][1] = (current.getNomClasse() == null || current.getNomClasse().trim().isEmpty() ? "" : (" " + current.getNomClasse()));
    						tableData[i][2] = (periode.getDateDebut() == null ? "" : (" " + periode.getDateDebut().get(GregorianCalendar.DAY_OF_MONTH)+"/"+(periode.getDateDebut().get(GregorianCalendar.MONTH)+1)+"/"+periode.getDateDebut().get(GregorianCalendar.YEAR)));
    						tableData[i][3] = (periode.getDateFin() == null ? "" : (" " + periode.getDateFin().get(GregorianCalendar.DAY_OF_MONTH)+"/"+(periode.getDateFin().get(GregorianCalendar.MONTH)+1)+"/"+periode.getDateFin().get(GregorianCalendar.YEAR)));
    						tableData[i][4] = (Double.toString(pourcent) == null || Double.toString(pourcent).trim().isEmpty() ? "" : (" " + pourcent*100+"%"));
    						tableData[i][5] = current;
    					}
    				}
    			};
    		};
    		classePeriodeModel.setColumnNames(periodeColumnNames);
    		classePeriodeModel.setLongValues(periodeColumnTypes);
    		classePeriodeModel.fillTable(new ArrayList<Object>(classePeriodeList));                					
     
    		log.debug("Fin de l'initialisation du tableau des classes - périodes");
     
    		//Setup du model et des colonnes
    		table.setModel(classePeriodeModel);
    		table.getColumn(0).setCellRenderer(new LierCellRenderer());
    		table.setUpColumns(SwingConstants.CENTER, new String[]{bundle.getString("gestion.classe.periode.label.lier"), bundle.getString("gestion.classe.periode.label.classe"), bundle.getString("gestion.classe.periode.label.date.debut"), bundle.getString("gestion.classe.periode.label.date.fin"), bundle.getString("gestion.classe.periode.label.pourcentage"),"Beans"});
    		table.setUpColumn( 4, SwingConstants.CENTER, bundle.getString("gestion.classe.periode.label.pourcentage"), -1);
    		table.setUpColumn( 3, SwingConstants.CENTER, bundle.getString("gestion.classe.periode.label.date.fin"), -1);
    		table.setUpColumn( 2, SwingConstants.CENTER, bundle.getString("gestion.classe.periode.label.date.debut"), -1);
    		table.setUpColumn( 1, SwingConstants.CENTER, bundle.getString("gestion.classe.periode.label.classe"), -1);
    		table.setUpColumn( 0, SwingConstants.CENTER, bundle.getString("gestion.classe.periode.label.lier"), 35);
     
    		//initialisation de l'option du tri
    		if(table.getRowCount() > 0){
    			TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
    			table.setRowSorter(sorter);
    		}else{
    			table.setRowSorter(null);
    		}
     
    		TableColumnModel tableColumnModel =  table.getColumnModel();
     
    		//Variable contenant les différentes colonnes
    		TableColumn[] columns = new TableColumn[table.getColumnCount()];
     
    		//Remplissage du tableau columns
    		for (int i = 0; i < columns.length; i++) {
    			columns[i] = table.getColumnModel().getColumn(i);
    		}
     
    		table.setFont(tableauFont);
    		table.getTableHeader().setFont(tableauFont);
     
    		tableColumnModel.removeColumn(columns[5]);
    	}
    //Déclaration de mes colum names et type
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    private String[] periodeColumnNames = new String[]{bundle.getString("gestion.classe.periode.label.lier"), bundle.getString("gestion.classe.periode.label.classe"), bundle.getString("gestion.classe.periode.label.date.debut"), bundle.getString("gestion.classe.periode.label.date.fin"), bundle.getString("gestion.classe.periode.label.pourcentage"), "Bean"};
    	private Object[] periodeColumnTypes = new Object[]{"Boolean", "String", "String", "String", "String", new Object()};

  2. #2
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2013
    Messages : 35
    Par défaut
    Bonjour,

    Je sais pas a quoi ressemble ton "LierCellRenderer()", je l'ai pas vue (un oublie visuel de ma part? ) Mais il est possible que se soit cette classe qui soit mal déclarée.
    Mais se n'est qu'une supposition.

  3. #3
    Membre éclairé Avatar de aljessy
    Homme Profil pro
    Développeur Java
    Inscrit en
    Octobre 2010
    Messages
    319
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : Cameroun

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2010
    Messages : 319
    Par défaut
    Voici la classe LierCellRenderer

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class LierCellRenderer extends DefaultTableCellRenderer {
     
        private static final long serialVersionUID = 1L;
     
        public Component getTableCellRendererComponent(CurveJTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
            if (value instanceof CurveJComboBox) {
                return (CurveJComboBox) value;
            }
            if (value instanceof Boolean) {
            	CurveJCheckBox cb = new CurveJCheckBox();
                cb.setSelected(((Boolean) value).booleanValue());
                return cb;
            }
            if (value instanceof CurveJCheckBox) {
                return (CurveJCheckBox) value;
            }
            return new CurveJTextField(value.toString());
        }
     
    }

  4. #4
    Membre averti
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2013
    Messages
    35
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2013
    Messages : 35
    Par défaut
    Bon, désolé mais je suis assez mauvais ( j'ai commencé le Swing que récemment).Et je vois pas vraiment de problème.
    Mais je viens de lire un tutoriel sur un autre site qui disait que pour les booleans, l'affichage est automatique.
    Si ça peu t'aider.
    Désolé de pas pouvoir faire mieux.
    Et bonne chance.

Discussions similaires

  1. Problème avec des insertions massives dans un ldap
    Par felix79 dans le forum Développement
    Réponses: 0
    Dernier message: 08/07/2011, 12h00
  2. Problème avec l'insertion dans une ArrayList
    Par LoveIinfo dans le forum Collection et Stream
    Réponses: 7
    Dernier message: 08/06/2011, 22h29
  3. Problème avec l'insertion d'une image dans JPanel
    Par anutka dans le forum AWT/Swing
    Réponses: 1
    Dernier message: 16/03/2006, 10h02
  4. [C#] problème avec l'insertion des données dans MySQL
    Par madica dans le forum Accès aux données
    Réponses: 7
    Dernier message: 08/11/2005, 13h27
  5. [MFC] problème avec les insertions dans CComboBox
    Par Joeleclems dans le forum MFC
    Réponses: 12
    Dernier message: 11/06/2004, 15h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo