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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
| import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
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.DefaultTableModel;
import javax.swing.table.TableModel;
public class JTableModelExemple {
public static void main(String[] args) {
// on créé une frame
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// on créé une JTable que l'on met dans un JPanel (un conteneur), avec entête et scrollpane
JTable table = new JTable();
table.setFillsViewportHeight(true);
JPanel tablePanel = new JPanel(new BorderLayout());
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
tablePanel.add(new JScrollPane(table));
// un renderer spécial
table.setDefaultRenderer(Couleur.class, new ColorCellRenderer());
// on met le conteneur de table dans le content pane de la frame
frame.add(tablePanel); // raccourci équivalent à frame.getContentPane().add(tablePanel);
// je créé un panel (un conteneur) avec trois boutons
JPanel buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets=new Insets(5,0,5,5);
JButton button1 = new JButton("Exemple 1");
button1.addActionListener(e-> table.setModel(createModelType1()));
buttonPanel.add(button1,gbc);
JButton button2 = new JButton("Exemple 2");
button2.addActionListener(e-> table.setModel(createModelType2()));
buttonPanel.add(button2,gbc);
JButton button3 = new JButton("Exemple 3");
button3.addActionListener(e-> table.setModel(createModelType3()));
buttonPanel.add(button3,gbc);
JButton button4 = new JButton("Exemple 4");
button4.addActionListener(e-> table.setModel(createModelType4()));
buttonPanel.add(button4,gbc);
// on met le conteneur de boutons dans le content pane de la frame (au sud, soit en bas)
frame.add(buttonPanel, BorderLayout.SOUTH);
// on affiche la fenêtre
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static TableModel createModelType1() {
// un exemple de modèle simple avec un paramétrage par défaut (plus ou moins ce que tu obtiens en faisant new JTable(data, columns)
// les titres des colonnnes
String[] columns = {"Colonne 1","Colonne 2","Colonne 3"};
// des datas : je génère 100 lignes de données aléatoires
String[] strings = {"Truc","Machin","Bidule"};
Object[][] data = Stream.generate(()-> new Object[] {
ThreadLocalRandom.current().nextInt(-100, 100),
strings[ThreadLocalRandom.current().nextInt(strings.length)],
ThreadLocalRandom.current().nextBoolean()
})
.limit(100)
.toArray(Object[][]::new);
return new DefaultTableModel(data, columns);
}
private static TableModel createModelType2() {
// un exemple de modèle un peu plus personnalisé, mais en se basant sur le modèle par défaut, par extension anonyme
// tu remarqueras que je génére les mêmes data que dans l'exemple 1
// les titres des colonnnes
String[] columns = {"Colonne 1","Colonne 2","Colonne 3"};
// des datas : je génère 100 lignes de données aléatoires
String[] strings = {"Truc","Machin","Bidule"};
Object[][] data = Stream.generate(()-> new Object[] {
ThreadLocalRandom.current().nextInt(-100, 100),
strings[ThreadLocalRandom.current().nextInt(strings.length)],
ThreadLocalRandom.current().nextBoolean()
})
.limit(100)
.toArray(Object[][]::new);
return new DefaultTableModel(data, columns) {
private static final long serialVersionUID = 1L;
// je ne fais que préciser les types des données
public java.lang.Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:
return Integer.class;
case 1:
return String.class;
case 2:
return Boolean.class;
default:
throw new IllegalStateException();
}
};
// je ne permets que la modification de la troisième colonne
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex==2;
}
};
}
private static TableModel createModelType3() {
// un exemple de modèle encore plus personnalisé, mais en se basant sur le modèle par défaut, par extension anonyme
// tu remarqueras que je génére les mêmes data que dans l'exemple 1
// des datas
// je génère 100 lignes de données aléatoires
String[] strings = {"Truc","Machin","Bidule"};
Object[][] data = Stream.generate(()-> new Object[] {
ThreadLocalRandom.current().nextInt(-100, 100),
strings[ThreadLocalRandom.current().nextInt(strings.length)],
ThreadLocalRandom.current().nextBoolean()
})
.limit(100)
.toArray(Object[][]::new);
return new DefaultTableModel() {
public int getColumnCount() {
return 4;
}
public String getColumnName(int columnIndex) {
return "Colonne " + (columnIndex+1);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public int getRowCount() {
return data.length;
}
public java.lang.Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:
return Integer.class;
case 1:
return Integer.class;
case 2:
return String.class;
case 3:
return Boolean.class;
default:
throw new IllegalStateException();
}
};
public Object getValueAt(int row, int columnIndex) {
switch(columnIndex) {
case 0:
return row+1;
default:
return data[row][columnIndex-1];
}
}
};
}
private static TableModel createModelType4() {
// un modèle complètement personnalisé (et ce n'est qu'un exemple, on peut faire beaucoup plus dynamique (généré automatiquement avec le résultat d'une requête SQL par exemple)
List<Vehicule> vehicules = new ArrayList<>();
vehicules.add(new Vehicule("Mercedes-Benz SL 65 AMG Black Serie", 10000000, LocalDate.of(2016, 11, 17), Couleur.ROUGE ));
vehicules.add(new Vehicule("Gumpert Apollo S", 12000000, LocalDate.of(2017, 8, 5), Couleur.JAUNE));
vehicules.add(new Vehicule("Pagani Huayra", 15000000, LocalDate.of(2016, 3, 23), Couleur.ROUGE));
vehicules.add(new Vehicule("Koenisegg Agera R", 13500000, LocalDate.of(2017, 6, 6), Couleur.BLEU));
vehicules.add(new Vehicule("SSC Tuatara", 23500000, LocalDate.of(2017, 9, 26), Couleur.BLANC));
return new AbstractTableModel() {
private DateTimeFormatter format = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Vehicule vehicule = vehicules.get(rowIndex);
switch(columnIndex) {
case 0:
return vehicule.getNom();
case 1:
return vehicule.getCouleur();
case 2:
return vehicule.getPrix();
case 3:
return Period.between(vehicule.getDateAchat(), LocalDate.now()).getMonths();
case 4:
return format.format(vehicule.getDateAchat());
default:
throw new IllegalStateException();
}
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
Vehicule vehicule = vehicules.get(rowIndex);
switch(columnIndex) {
case 2:
if ( value instanceof Integer ) {
vehicule.setPrix((Integer)value);
break;
}
default:
throw new IllegalStateException();
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:
return String.class;
case 1:
return Couleur.class;
case 2:
return Integer.class;
case 3:
return Integer.class;
case 4:
return String.class;
default:
throw new IllegalStateException();
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex==2; // je permet de modifier le prix uniquement uniquement (c'est juste pour l'exemple)
}
@Override
public int getRowCount() {
return vehicules.size();
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public String getColumnName(int columnIndex) {
switch(columnIndex) {
case 0:
return "Modèle";
case 1:
return "Couleur";
case 2:
return "Prix de vente (Euros)";
case 3:
return "Age (Mois)";
case 4:
return "Date d'achat";
default:
throw new IllegalStateException();
}
}
};
}
public static class Vehicule {
private String nom;
private int prix;
private LocalDate dateAchat;
private Couleur couleur;
public Vehicule(String nom, int prix, LocalDate dateAchat, Couleur couleur) {
this.nom=nom;
this.prix=prix;
this.dateAchat=dateAchat;
this.couleur=couleur;
}
public String getNom() {
return nom;
}
public int getPrix() {
return prix;
}
public void setPrix(int prix) {
this.prix=prix;
}
public LocalDate getDateAchat() {
return dateAchat;
}
public Couleur getCouleur() {
return couleur;
}
}
public static enum Couleur {
ROUGE("rouge",Color.decode("#FE2E2E")),
BLANC("blanche",Color.WHITE),
BLEU("Bleue",Color.decode("#0404B4")),
JAUNE("Jaune",Color.decode("#F4FA58"));
private String nom;
private Image image;
private Couleur(String nom, Color color) {
this.nom=nom;
this.image=createImage(color);
}
private static Image createImage(Color color) {
BufferedImage image = new BufferedImage(14, 14, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
try {
g.setColor(Color.DARK_GRAY);
g.drawRect(0,0,13,13);
g.setColor(color);
g.fillRect(1,1,12,12);
}
finally {
g.dispose();
}
return image;
}
public Image getImage() {
return image;
}
public String getNom() {
return nom;
}
}
public static class ColorCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
public ColorCellRenderer() {
super();
}
@Override
protected void setValue(Object value) {
if ( value instanceof Couleur ) {
Couleur couleur = (Couleur) value;
super.setValue(couleur.getNom());
setIcon(new ImageIcon(couleur.getImage()));
}
else {
setIcon(null);
super.setValue(null);
}
}
}
} |
Partager