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 :

[JTable] Un tableau dynamique (ajout de lignes)


Sujet :

Composants Java

  1. #1
    Membre éprouvé
    Profil pro
    Responsable Dev
    Inscrit en
    Décembre 2003
    Messages
    788
    Détails du profil
    Informations personnelles :
    Localisation : France, Vendée (Pays de la Loire)

    Informations professionnelles :
    Activité : Responsable Dev

    Informations forums :
    Inscription : Décembre 2003
    Messages : 788
    Points : 1 063
    Points
    1 063
    Par défaut [JTable] Un tableau dynamique (ajout de lignes)
    Bonjour a Tous
    voila j'ai un problème avec JTable.
    Dans mon appli je doit réaliser un tableau avec des Chekbox et des JComboBox
    j'ai trouver sur sun un super exemple qui fonctionne très bien
    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
     
    /*
     * TableRenderDemo.java is a 1.4 application that requires no other files.
     */
     
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
     
    /** 
     * TableRenderDemo is just like TableDemo, except that it
     * explicitly initializes column sizes and it uses a combo box
     * as an editor for the Sport column.
     */
    public class TableRenderDemo extends JPanel {
        private boolean DEBUG = false;
     
        public TableRenderDemo() {
            super(new GridLayout(1,0));
     
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
     
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
     
            //Set up column sizes.
            initColumnSizes(table);
     
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table, table.getColumnModel().getColumn(2));
     
            //Add the scroll pane to this panel.
            add(scrollPane);
        }
     
        /*
         * This method picks good column sizes.
         * If all column heads are wider than the column's cells'
         * contents, then you can just use column.sizeWidthToFit().
         */
        private void initColumnSizes(JTable table) {
            MyTableModel model = (MyTableModel)table.getModel();
            TableColumn column = null;
            Component comp = null;
            int headerWidth = 0;
            int cellWidth = 0;
            Object[] longValues = model.longValues;
            TableCellRenderer headerRenderer =
                table.getTableHeader().getDefaultRenderer();
     
            for (int i = 0; i < 5; i++) {
                column = table.getColumnModel().getColumn(i);
     
                comp = headerRenderer.getTableCellRendererComponent(
                                     null, column.getHeaderValue(),
                                     false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
     
                comp = table.getDefaultRenderer(model.getColumnClass(i)).
                                 getTableCellRendererComponent(
                                     table, longValues[i],
                                     false, false, 0, i);
                cellWidth = comp.getPreferredSize().width;
     
                if (DEBUG) {
                    System.out.println("Initializing width of column "
                                       + i + ". "
                                       + "headerWidth = " + headerWidth
                                       + "; cellWidth = " + cellWidth);
                }
     
                //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
                column.setPreferredWidth(Math.max(headerWidth, cellWidth));
            }
        }
     
        public void setUpSportColumn(JTable table,
                                     TableColumn sportColumn) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
            comboBox.addItem("Snowboarding");
            comboBox.addItem("Rowing");
            comboBox.addItem("Knitting");
            comboBox.addItem("Speed reading");
            comboBox.addItem("Pool");
            comboBox.addItem("None of the above");
            sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
     
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            sportColumn.setCellRenderer(renderer);
        }
     
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};
            private Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            };
     
            public final Object[] longValues = {"Sharon", "Campione",
                                                "None of the above",
                                                new Integer(20), Boolean.TRUE};
     
            public int getColumnCount() {
                return columnNames.length;
            }
     
            public int getRowCount() {
                return data.length;
            }
     
            public String getColumnName(int col) {
                return columnNames[col];
            }
     
            public Object getValueAt(int row, int col) {
                return data[row][col];
            }
     
            /*
             * JTable uses this method to determine the default renderer/
             * editor for each cell.  If we didn't implement this method,
             * then the last column would contain text ("true"/"false"),
             * rather than a check box.
             */
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            }
     
            /*
             * Don't need to implement this method unless your table's
             * editable.
             */
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
                }
            }
     
            /*
             * Don't need to implement this method unless your table's
             * data can change.
             */
            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() + ")");
                }
     
                data[row][col] = value;
                fireTableCellUpdated(row, col);
     
                if (DEBUG) {
                    System.out.println("New value of data:");
                    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("  " + data[i][j]);
                    }
                    System.out.println();
                }
                System.out.println("--------------------------");
            }
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
     
            //Create and set up the window.
            JFrame frame = new JFrame("TableRenderDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Create and set up the content pane.
            TableRenderDemo newContentPane = new TableRenderDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    mais voila maintenant je voudrais ajouter des lignes
    mais avec cet abstractModel je n'ai pas addRow
    j'ai bien essayer d'écrire une fonction addRow qui modifie l'objet Data mais impossible quelqu'un peux t-il m'aider
    merci

  2. #2
    Membre expérimenté Avatar de herve91
    Profil pro
    Inscrit en
    Novembre 2004
    Messages
    1 282
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2004
    Messages : 1 282
    Points : 1 608
    Points
    1 608
    Par défaut
    Le modèle de données que tu utilises ne permet pas (facilement) en l'état de modifier le nombre de lignes. Je te conseillerais d'utiliser un ArrayList plutôt qu'un Object[][].
    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
     
    static class Person {
      String firstName;
      String lastName;
      String sport;
      Integer years;
      Boolean vegetarian;
     
      public Person(String firstName,
                    String lastName,
                    String sport,
                    int years,
                    boolean vegetarian) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.sport = sport;
        this.years = new Integer(years);
        this.vegetarian = Boolean.valueOf(vegetarian);
      }
     
      public String toString() {
        return firstName + " " + lastName + " " + sport + " " + years + " " + vegetarian;
      }
    };
     
    class MyTableModel extends AbstractTableModel { 
            private String[] columnNames = {"First Name", 
                                            "Last Name", 
                                            "Sport", 
                                            "# of Years", 
                                            "Vegetarian"};
            private ArrayList data = setData();
     
            private ArrayList setData() {
                ArrayList data = new ArrayList();
     
                data.add(new Person("Mary", "Campione", 
                                    "Snowboarding", 5, false)); 
                data.add(new Person("Alison", "Huml", 
                                    "Rowing", 3, true));
                data.add(new Person("Kathy", "Walrath", 
                                    "Knitting", 2, false));
                data.add(new Person("Sharon", "Zakhour", 
                                    "Speed reading", 20, true));
                data.add(new Person("Philip", "Milne", 
                                    "Pool", 10, false));
                return data;
            }; 
     
            public final Person longValues = new Person("Sharon", "Campione", 
                                                        "None of the above",  20, true); 
     
            public int getColumnCount() { 
                return columnNames.length; 
            } 
     
            public int getRowCount() { 
                return data.size(); 
            } 
     
            public String getColumnName(int col) { 
                return columnNames[col]; 
            } 
     
            public Object getValueAt(int row, int col) { 
                Person person = (Person) data.get(row);
                switch (col) {
                case 0: return person.firstName;
                case 1: return person.lastName;
                case 2: return person.sport;
                case 3: return person.years;
                case 4: return person.vegetarian;
                } 
            } 
     
            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() + ")"); 
                } 
     
                Person person = (Person) data.get(row);
                switch (col) {
                case 0: person.firstName = (String) value;
                case 1: person.lastName = (String) value;
                case 2: person.sport = (String) value;
                case 3: person.years = (Integer) value;
                case 4: person.vegetarian = (Boolean) value;
                }
                fireTableCellUpdated(row, col); 
     
                if (DEBUG) { 
                    System.out.println("New value of data:"); 
                    printDebugData(); 
                } 
            } 
     
     
            public void addRow(Person person) {
              addRow(getRowCount(), person);
            }
     
            public void addRow(int pos, Person person) {
              data.add(pos, person);
              fireTableRowsInserted(pos, pos);
            }
     
            public void addRow(String firstName,
                               String lastName,
                               String sport,
                               int years,
                               boolean vegetarian) {
              addRow(getRowCount(),
                     new Person(firstName, lastName,
                                sport, years, vegetarian);
            }
     
            public void addRow(int pos,
                               String firstName,
                               String lastName,
                               String sport,
                               int years,
                               boolean vegetarian) {
              addRow(pos,
                     new Person(firstName, lastName,
                                sport, years, vegetarian));
            }
     
            private void printDebugData() { 
                int numRows = getRowCount();
     
                for (int i=0; i < numRows; i++) { 
                    System.out.println("    row " + i + ":" + data.get(row));
                } 
                System.out.println("--------------------------"); 
            } 
        }

  3. #3
    Membre à l'essai
    Homme Profil pro
    Inscrit en
    Juillet 2002
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Juillet 2002
    Messages : 18
    Points : 22
    Points
    22
    Par défaut
    Salut,
    au lieu d'hériter de AbstractTableModel, fais un extends de DefaultTableModel et tu auras accès aux méthodes addRow(Vector) et addRows(Object[]) pour l'ajout dynamique de lignes dans ton modèle.

  4. #4
    Membre à l'essai
    Inscrit en
    Octobre 2005
    Messages
    18
    Détails du profil
    Informations forums :
    Inscription : Octobre 2005
    Messages : 18
    Points : 10
    Points
    10
    Par défaut Salut
    Pour ne pas trop te compliquer la vie, voila après avoir crée ta table fait ceci
    Matable.setModel(ModalTask);
    Ou ModalTask est d’une variable déclaré comme suit :
    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
      public DefaultTableModel  ModalTask = new DefaultTableModel(
                new Object [][] { },
                new String []   { "Code", "Nom", "Prenom","Dériner délais" }
            ) {
                Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class,java.lang.String.class
                };
                boolean[] canEdit = new boolean [] {
                    false, false, false, false
                };
     
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }
     
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            };
    Après au lieu de manipuler la variable Matable tu manipules la variable ModalTask, ainsi tu auras accès à AddRow et tous ce qui va avec .

Discussions similaires

  1. JTable dynamique : ajouter des lignes
    Par koolway dans le forum Composants
    Réponses: 6
    Dernier message: 17/06/2010, 15h41
  2. tableau dynamique (ajout de lignes)
    Par nanourene dans le forum Struts 1
    Réponses: 3
    Dernier message: 29/04/2009, 10h18
  3. [JS/PHP] Formulaire dynamique : ajout de ligne et requete SQL
    Par Argol dans le forum Général JavaScript
    Réponses: 29
    Dernier message: 11/03/2009, 03h22
  4. [MySQL] Tableau dynamique et couleur ligne
    Par Jumano dans le forum PHP & Base de données
    Réponses: 2
    Dernier message: 26/03/2007, 20h57
  5. [tableau dynamique]numéro de ligne
    Par trach.sam dans le forum Général JavaScript
    Réponses: 7
    Dernier message: 26/05/2006, 10h12

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