Bonne rencontre,
J'ai un petit soucis avec une JTable couplée avec une base de données.
Quand je modifie une donnée et que je clique sur le bouton sauver. Celle-ci est bien modifiée dans la JTable et dans la base de données.
Quand je supprime une donnée et je clique sur le bouton sauver. Celle-ci est bien supprimée de la JTable et de la base de données. Mais il y a un blanc dans la JTable.
Par contre quand je crée un nouveau enregistrement et que je clique sur le bouton sauver. L'information n'est pas rafraîchie dans la JTable mais elle est bien enregistrée dans la base de données.
Je suppose que c'est par ce que je fais mal mon rafraîchissement dans la JTable et qu'il ne met pas a jour le nombre de ligne. J'ai testé ce genre de méthode fireTableDataChanged(); dans mon model perso au niveau de public void setData mais quand je fais ça... La table se rafraîchit bien après un nouveau enregistrement mais plus quand je modifie ou supprime une donnée et je reçois ce message d'erreur dans la console.
Voici une partie de mon code :Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at be.roose.model.MaTableModel.getValueAt(MaTableModel.java:35)
Mon model
Ma vue
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 package be.roose.model; import javax.swing.table.AbstractTableModel; // Modele pour les tables public class MaTableModel extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; /** Objet qui contient les résultats de la table */ private Object[][]data; private String[] tableColumnsName; private boolean DEBUG = false; public MaTableModel(Object[][] donnee, String[] col){ this.data = donnee; this.tableColumnsName = col; } public int getColumnCount() { return tableColumnsName.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return tableColumnsName[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } /* * La JTable utilsie cette méthode pour détermniner le default renderer * Elle permet de remplacer les true/false par des checkbox */ public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Methode qui permet d'accorder ou non l'édition * */ public boolean isCellEditable(int row, int col) { //On refuse l'édition des tables return false; } public void setDEBUG(boolean debug) { DEBUG = debug; } /* * 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("--------------------------"); } public void setData(Object[][] data,String[] col) { this.data = data ; this.tableColumnsName = col; fireTableDataChanged(); } }
Model DAO
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276 package be.roose.vue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import be.roose.connexion.ConnexionDB; import be.roose.connexion.DbParametre; import be.roose.model.ChambreDAO; import be.roose.model.ChambreDAOImpl; import be.roose.model.ChambreTO; import be.roose.model.MaTableModel; /** * @author Raphaël Roose * Cette classe sert a affiché et a effectuer des opérations sur la table Chambre * */ public class DesktopChambreListe extends JInternalFrame implements ActionListener,ListSelectionListener{ /** * */ private static final long serialVersionUID = 1L; private JPanel monPanel = new JPanel(); private GridBagConstraints gbc = new GridBagConstraints(); private JScrollPane maScrollPane; private JTable maTable; private String[] tableColumnsName = {"ID","Numero Chambre","Numero Tel","Libre"}; private JLabel numeroChambreLabel = new JLabel("Numero de Chambre"); private JLabel telChambreLabel = new JLabel("Tel chambre"); private JLabel libreChambreLabel = new JLabel("Libre"); private JTextField numeroChambreField = new JTextField(); private JTextField telChambreField = new JTextField(); private JComboBox libreChambreCombo = new JComboBox(); private JButton quitterBouton = new JButton("Quitter"); private JButton sauverBouton = new JButton("sauver"); private JButton nouveauBouton = new JButton("Nouveau"); private JButton supprimerBouton = new JButton("Supprimer"); private boolean statut = true; private int id; private ChambreDAO chambreDAO; private MaTableModel monModel; public DesktopChambreListe(){ this.setTitle("Liste des Chambres"); this.setClosable(true); this.setResizable(true); this.setSize(790, 500); this.moveToFront(); this.setVisible(true); System.out.println("Chambre!"); // On récupére les informations de la base de donnée pour établir la connexion ConnexionDB dbConf = new ConnexionDB(); DbParametre dbParametre = null; try { dbParametre=dbConf.processProperties(); } catch (IOException e1) { e1.printStackTrace(); System.exit(1); } if (dbParametre == null) { System.out.println("Pas d'information sur la DB!"); System.exit(1); } chambreDAO = new ChambreDAOImpl(dbParametre); // Méthode pour obtenir les enregistements chambreDAO.scanAllChambreDB(); // On donne les données et on crée un model personnalisé pour la table monModel = new MaTableModel(chambreDAO.getData(),tableColumnsName); maTable = new JTable(monModel); // Selection par ligne maTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); maScrollPane = new JScrollPane(maTable); // On défnit la combo libreChambreCombo.addItem("Oui"); libreChambreCombo.addItem("Non"); // On définit le Grid monPanel.setLayout(new GridBagLayout()); // On place les Label gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets (10,10,10,10); gbc.gridx = 0; gbc.gridy = 6; monPanel.add(numeroChambreLabel,gbc); gbc.gridx = 0; gbc.gridy = 7; monPanel.add(telChambreLabel,gbc); gbc.gridx = 0; gbc.gridy = 8; monPanel.add(libreChambreLabel,gbc); // On place les TextField gbc.gridx = 1; gbc.gridy = 6; gbc.weightx=50; monPanel.add(numeroChambreField,gbc); gbc.gridx = 1; gbc.gridy = 7; monPanel.add(telChambreField,gbc); gbc.gridx = 1; gbc.gridy = 8; monPanel.add(libreChambreCombo,gbc); // On place les boutons gbc.weightx=0; gbc.weighty=0; gbc.gridx = 2; gbc.gridy = 9; monPanel.add(nouveauBouton,gbc); gbc.gridx = 3; gbc.gridy = 9; monPanel.add(supprimerBouton,gbc); gbc.gridx = 4; gbc.gridy = 9; monPanel.add(sauverBouton,gbc); gbc.gridx = 5; gbc.gridy = 9; monPanel.add(quitterBouton,gbc); // On place la table gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 6; gbc.gridheight = 6; gbc.weightx=100; gbc.weighty=100; monPanel.add(maScrollPane,gbc); // On attache monPanel this.getContentPane().add(monPanel); // Ecouteur quitterBouton.addActionListener(this); nouveauBouton.addActionListener(this); sauverBouton.addActionListener(this); supprimerBouton.addActionListener(this); maTable.getSelectionModel().addListSelectionListener(this); } public ChambreDAO getChambreDAO() { return chambreDAO; } public void setChambreDAO(ChambreDAO chambreDAO) { this.chambreDAO = chambreDAO; } // Méthode qui vide les champs public void vide(){ this.numeroChambreField.setText(""); this.telChambreField.setText(""); this.libreChambreCombo.setSelectedIndex(0); } @Override public void actionPerformed(ActionEvent event) { if (event.getSource()==quitterBouton){ // On ferme la JInternalFrame this.dispose(); } else if (event.getSource()==nouveauBouton){ // On vide les champs vide(); this.statut = true; } else if(event.getSource()==sauverBouton){; ChambreTO laChambre = new ChambreTO(); laChambre.setId(id); laChambre.setNumeroChambre(Integer.parseInt(this.numeroChambreField.getText())); laChambre.setTelChambre(this.telChambreField.getText()); if (this.libreChambreCombo.getSelectedItem().equals("Oui"))laChambre.setLibreChambre(true); else laChambre.setLibreChambre(false); // // On check le statut si true nouveau enregistrement si false update if (this.statut==true) { getChambreDAO().insertChambreDB(laChambre) ; vide(); } else { getChambreDAO().updateChambreDB(laChambre); vide(); this.statut=true; } // Méthode pour obtenir les enregistements chambreDAO.scanAllChambreDB(); monModel.setData(chambreDAO.getData(),tableColumnsName); maTable.setModel(monModel); maTable.repaint(); } else if (event.getSource()==supprimerBouton){ JOptionPane info = new JOptionPane(); ImageIcon img = new ImageIcon("img/warning.gif"); // On regarde si on bien sélectionner une ligne if(this.numeroChambreField.getText().equals("")) info.showMessageDialog(null, "Vous devez d'abord sélectionner un champ", "Attention",JOptionPane.WARNING_MESSAGE, img); else { img = new ImageIcon("img/info.gif"); int option = info.showConfirmDialog(null, "Voulez-vous vraiment supprimer l'entregistrement?", "Suppression", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,img); // On regarde le choix if (option==0){ ChambreTO laChambre = new ChambreTO(); laChambre.setId(id); getChambreDAO().deleteChambreDB(laChambre); // Méthode pour obtenir les enregistements chambreDAO.scanAllChambreDB(); monModel.setData(chambreDAO.getData(),tableColumnsName); maTable.setModel(monModel); maTable.repaint(); } else vide(); } } } @Override public void valueChanged(ListSelectionEvent event) { // TODO Auto-generated method stub // on met le statut à False pour dire que c'est un update si on clique sur sauver this.statut = false; //On remplit les champs selon la sélection int viewRow = this.maTable.getSelectedRow(); this.id = Integer.parseInt(maTable.getValueAt(viewRow, 0).toString()); this.numeroChambreField.setText(maTable.getValueAt(viewRow, 1).toString()); this.telChambreField.setText(maTable.getValueAt(viewRow, 2).toString()); if (maTable.getValueAt(viewRow, 3).equals(true))this.libreChambreCombo.setSelectedIndex(0); else this.libreChambreCombo.setSelectedIndex(1); } }
Merci pour votre aide.
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 package be.roose.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import be.roose.connexion.DbParametre; import be.roose.query.MesQuery; public class ChambreDAOImpl implements ChambreDAO { /** Connexion à la base de données */ private Connection connexion; /** Statement pour les query */ private Statement statement; /** Results of the scanning of the database */ private ResultSet resultSet; /** Parametres to access the database */ private DbParametre dbParametre; /** Parametre de la query */ private MesQuery maQuery; /** Objet qui contient les résultats de la table */ private Object[][]data; /** Constructeur de base */ public ChambreDAOImpl() { throw new UnsupportedOperationException( "Pour avoir accès au DB, les paramètres sont nécessaires "); } /** constructeur qui reçoit les paramètres de la base */ public ChambreDAOImpl(DbParametre dbParametre) { this.dbParametre = dbParametre; maQuery = new MesQuery("CHAMBRE"); } public Object[][] getData() { return this.data; } public void setData(Object[][] data) { this.data = data; } @Override public void deleteChambreDB(ChambreTO chambre) { // TODO Auto-generated method stub String sql; sql = maQuery.delChambre(chambre.getId()); int rows; System.out.println(sql); try { Class.forName(dbParametre.getProtocol()).newInstance(); connexion=DriverManager.getConnection(dbParametre.getUrldb() , dbParametre.getUser(), dbParametre.getPassword()); statement=connexion.createStatement(); rows=statement.executeUpdate(sql); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { connexion.close(); } catch (SQLException e) { e.printStackTrace(); } try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void insertChambreDB(ChambreTO chambre) { // TODO Auto-generated method stub String sql; sql = maQuery.insertionTable(chambre.getNumeroChambre(),chambre.getTelChambre(),chambre.getLibreChambre()); int rows; System.out.println(sql); try { Class.forName(dbParametre.getProtocol()).newInstance(); connexion=DriverManager.getConnection(dbParametre.getUrldb() , dbParametre.getUser(), dbParametre.getPassword()); statement=connexion.createStatement(); rows=statement.executeUpdate(sql); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { connexion.close(); } catch (SQLException e) { e.printStackTrace(); } try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void scanAllChambreDB() { try { Class.forName(dbParametre.getProtocol()).newInstance(); connexion=DriverManager.getConnection(dbParametre.getUrldb() , dbParametre.getUser(), dbParametre.getPassword()); statement=connexion.createStatement(); resultSet=statement.executeQuery(maQuery.voirTable()); ResultSetMetaData rsmd = resultSet.getMetaData(); int colNo = rsmd.getColumnCount(); //on place le curseur sur le dernier tuple resultSet.last(); //on récupère le numéro de la ligne int nombreLignes = resultSet.getRow(); //on repace le curseur avant la première ligne resultSet.beforeFirst(); Object[][] data = new Object[nombreLignes][colNo]; int i=0; while(resultSet.next()|| i<nombreLignes){ for(int j=0;j<colNo;j++){ data[i][j]=resultSet.getObject(j+1); } i++; } // On remplit la variable d'instance setData(data); } catch (InstantiationException e) { e.printStackTrace(); System.out.println("1"); } catch (IllegalAccessException e) { e.printStackTrace(); System.out.println("2"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("3"); } catch (SQLException e) { e.printStackTrace(); System.out.println("4"); } finally { try { connexion.close(); } catch (SQLException e) { e.printStackTrace(); } try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void updateChambreDB(ChambreTO chambre) { // TODO Auto-generated method stub String sql; sql = maQuery.majChambre(chambre.getId(),chambre.getNumeroChambre(),chambre.getTelChambre(),chambre.getLibreChambre()); int rows; System.out.println(sql); try { Class.forName(dbParametre.getProtocol()).newInstance(); connexion=DriverManager.getConnection(dbParametre.getUrldb() , dbParametre.getUser(), dbParametre.getPassword()); statement=connexion.createStatement(); rows=statement.executeUpdate(sql); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { connexion.close(); } catch (SQLException e) { e.printStackTrace(); } try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Raphaël.
Partager