-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckBoxTree.java
More file actions
1185 lines (1125 loc) · 31.1 KB
/
Copy pathCheckBoxTree.java
File metadata and controls
1185 lines (1125 loc) · 31.1 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileSystemView;
import javax.swing.Box;
import javax.swing.JTextField;
import javax.swing.JFileChooser;
import javax.swing.JDialog;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
import javax.swing.ActionMap;
import javax.swing.JComponent;
import javax.swing.InputMap;
import javax.swing.UIManager;
//import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Color;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Container;
import java.awt.LayoutManager;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Locale;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.text.Collator;
/**
* Type d'élément affiché dans l'explorateur.
*/
enum FileNodeType {
CURRENT_DIRECTORY,
PARENT_DIRECTORY,
DIRECTORY,
FILE
}
/**
* Objet représentant un élément de l'arbre.
*/
class FileNode {
private final File file;
private final FileNodeType type;
private final long size;
private final long lastModified;
public FileNode(File file, FileNodeType type) {
this.file = file;
this.type = type;
/*
* Récupération des métadonnées des fichiers.
*/
if (file != null && file.exists()) {
this.size = file.length();
this.lastModified = file.lastModified();
} else {
this.size = 0L;
this.lastModified = 0L;
}
}
public File getFile() {
return file;
}
public FileNodeType getType() {
return type;
}
public long getSize() {
return size;
}
public long getLastModified() {
return lastModified;
}
public boolean isDirectory() {
return type == FileNodeType.DIRECTORY
|| type == FileNodeType.PARENT_DIRECTORY;
}
public boolean isFile() {
return type == FileNodeType.FILE;
}
public boolean isParentDirectory() {
return type == FileNodeType.PARENT_DIRECTORY;
}
@Override
public String toString() {
if (isParentDirectory()) {
return ".." + FileSystems.getDefault().getSeparator();
}
return file.getName();
/*
switch (type) {
case CURRENT_DIRECTORY:
return file.getAbsolutePath();
case PARENT_DIRECTORY:
return "../";
case DIRECTORY:
case FILE:
default:
return file.getName();
}
*/
}
}
/**
* JTree personnalisé permettant de sélectionner les fichiers.
*/
class JCheckBoxTree extends JTree {
private final CheckBoxTreeCellRenderer renderer;
public JCheckBoxTree(DefaultTreeModel model) {
super(model);
renderer = new CheckBoxTreeCellRenderer();
setCellRenderer(renderer);
setRootVisible(true);
setShowsRootHandles(true);
setRowHeight(24);
}
/**
* Retourne le renderer utilisé par l'arbre.
*/
public CheckBoxTreeCellRenderer getCheckBoxRenderer() {
return renderer;
}
}
/**
* Renderer Swing de l'arbre.
*
* Affiche :
* [Checkbox] [Icône] [Nom] [Taille] [Dernière modification]
*
* Le renderer ne stocke PAS l'état de sélection.
* Il se contente d'afficher l'état fourni par le modèle.
*/
class CheckBoxTreeCellRenderer extends JPanel implements TreeCellRenderer {
private final JCheckBox checkBox;
private final JLabel iconLabel;
private final JLabel textLabel;
private final JLabel sizeLabel;
private final JLabel dateLabel;
private final FileSystemView fileSystemView;
private static final Color JAVA_BACKGROUND = new Color(255, 210, 210);
private static final Color OTHER_BACKGROUND = new Color(240, 240, 255);
private static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern(" dd/MM/yyyy HH:mm:ss");
public CheckBoxTreeCellRenderer() {
//setLayout(new BorderLayout(5, 0));
setLayout(new FileTreeRowLayout());
setOpaque(false);
fileSystemView = FileSystemView.getFileSystemView();
/*
* Checkbox.
*/
checkBox = new JCheckBox();
checkBox.setOpaque(false);
checkBox.setMargin(new Insets(0, 0, 0, 0)); // Évite que la checkbox possède une marge
/*
* Icône du fichier/dossier.
*/
iconLabel = new JLabel();
/*
* Nom du fichier/dossier.
*/
textLabel = new JLabel();
/*
* Taille du fichier
*/
sizeLabel = new JLabel();
sizeLabel.setHorizontalAlignment(JLabel.RIGHT); // Alignement à droite pour la taille.
/*
* Date de modification du fichier
*/
dateLabel = new JLabel();
dateLabel.setHorizontalAlignment(JLabel.LEFT); // La date est alignée à gauche.
//add(checkBox, BorderLayout.WEST);
//add(iconLabel, BorderLayout.CENTER);
//add(textLabel, BorderLayout.EAST);
add(checkBox);
add(iconLabel);
add(textLabel);
add(sizeLabel);
add(dateLabel);
}
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object userObject = node.getUserObject();
/*
* Nettoyage du renderer
*/
checkBox.setVisible(false);
checkBox.setSelected(false);
iconLabel.setIcon(null);
textLabel.setText("");
textLabel.setBackground(null);
textLabel.setForeground(Color.BLACK);
sizeLabel.setText("");
dateLabel.setText("");
/*
* Objet inattendu
*/
if (!(userObject instanceof FileNode)) {
textLabel.setText(String.valueOf(userObject));
return this;
}
FileNode fileNode = (FileNode) userObject;
File file = fileNode.getFile();
if (isRootNode(tree, node)) {
/*
* ============================
* En-tête du répertoire courant
* ============================
*/
checkBox.setVisible(true);
if (tree instanceof FileExplorerTree) {
FileExplorerTree fileTree = (FileExplorerTree) tree;
boolean retVal = fileTree.areAllFilesSelected();
//System.out.println(retVal);
checkBox.setSelected(fileTree.areAllFilesSelected());
}
/*
* Pas d'icône dans la colonne
* checkbox/icône pour l'en-tête.
*/
//iconLabel.setIcon(null);
iconLabel.setIcon(fileSystemView.getSystemIcon(file));
/*
* Nom du répertoire courant.
*/
textLabel.setText(fileNode.toString());
textLabel.setOpaque(false);
textLabel.setForeground(Color.BLACK);
textLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
/*
* En-tête de la colonne Taille.
*/
sizeLabel.setText("Size");
sizeLabel.setHorizontalAlignment(JLabel.RIGHT); // or LEFT
sizeLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
/*
* En-tête de la colonne Date.
*/
dateLabel.setText("Date modified");
dateLabel.setHorizontalAlignment(JLabel.RIGHT); // or RIGHT or CENTER
dateLabel.setFont(new Font("SansSerif", Font.BOLD, 12));
return this;
}
else {
textLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
sizeLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
dateLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
}
/*
* ============================
* Icône native
* ============================
*/
if (file != null) {
iconLabel.setIcon(fileSystemView.getSystemIcon(file));
}
/*
* ============================
* Nom
* ============================
*/
textLabel.setText(fileNode.toString());
/*
* ============================
* Checkbox
* ============================
*/
if (fileNode.isFile()) {
checkBox.setVisible(true);
if (tree instanceof FileExplorerTree) {
FileExplorerTree fileTree = (FileExplorerTree) tree;
checkBox.setSelected(fileTree.isFileSelected(file));
}
// Mise en évidence des fichiers Java.
if (file.getName().toLowerCase().endsWith(".java")) {
//textLabel.setOpaque(true);
textLabel.setBackground(JAVA_BACKGROUND);
textLabel.setForeground(Color.RED);
}
else {
//textLabel.setOpaque(false);
//textLabel.setOpaque(true);
textLabel.setBackground(OTHER_BACKGROUND);
textLabel.setForeground(Color.BLUE);
}
}
else {
// Dossiers
textLabel.setOpaque(false);
textLabel.setForeground(Color.BLACK);
}
/*
* ============================
* Taille & Date de modification
* ============================
*/
if (fileNode.isFile()) {
sizeLabel.setText(formatFileSize(fileNode.getSize()));
dateLabel.setText(formatLastModified(fileNode.getLastModified()));
}
else {
sizeLabel.setText(" "); // Pour les dossiers.
dateLabel.setText(" ");
}
return this;
}
private boolean isRootNode(JTree tree, DefaultMutableTreeNode node) {
Object root = tree.getModel().getRoot();
return root == node;
}
/**
* Convertit une taille exprimée en octets
* en une chaîne lisible.
*/
private String formatFileSize(long size) {
if (size < 1024) {
return size + " o";
}
if (size < 1024L * 1024L) {
return String.format("%.1f Ko", size / 1024.0);
}
if (size < 1024L * 1024L * 1024L) {
return String.format("%.1f Mo", size / (1024.0 * 1024.0));
}
return String.format("%.1f Go", size / (1024.0 * 1024.0 * 1024.0));
}
/**
* Convertit le timestamp de dernière
* modification en date/heure locale.
*/
private String formatLastModified(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return DATE_FORMATTER.format(dateTime);
}
}
/**
* Layout horizontal spécialisé pour les lignes du JTree.
* Colonnes :
* [Checkbox] [Icône] [Nom] [Taille] [Dernière modification]
* Les largeurs sont fixes, ce qui permet d'obtenir un véritable
* alignement vertical entre les différentes lignes du JTree.
*/
class FileTreeRowLayout implements LayoutManager {
/*
* Largeurs des colonnes.
*/
public static final int CHECKBOX_WIDTH = 30;
public static final int ICON_WIDTH = 32;
public static final int NAME_WIDTH = 300;
public static final int SIZE_WIDTH = 100;
public static final int DATE_WIDTH = 150;
/*
* Hauteur d'une ligne.
*/
private static final int ROW_HEIGHT = 24;
@Override
public void addLayoutComponent(String name, Component comp) {
// Rien à faire.
}
@Override
public void removeLayoutComponent(Component comp) {
// Rien à faire.
}
@Override
public Dimension preferredLayoutSize(Container parent) {
int width = CHECKBOX_WIDTH + ICON_WIDTH + NAME_WIDTH + SIZE_WIDTH + DATE_WIDTH;
return new Dimension(width, ROW_HEIGHT);
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
@Override
public void layoutContainer(Container parent) {
int x = 0;
int height = parent.getHeight();
Component[] components = parent.getComponents();
/*
* Ordre attendu :
* 0 = checkbox
* 1 = icône
* 2 = nom
* 3 = taille
* 4 = date
*/
if (components.length > 0) {
components[0].setBounds(x, 0, CHECKBOX_WIDTH, height);
x += CHECKBOX_WIDTH;
}
if (components.length > 1) {
components[1].setBounds(x, 0, ICON_WIDTH, height);
x += ICON_WIDTH;
}
if (components.length > 2) {
components[2].setBounds(x, 0, NAME_WIDTH, height);
x += NAME_WIDTH;
}
if (components.length > 3) {
components[3].setBounds(x, 0, SIZE_WIDTH, height);
x += SIZE_WIDTH;
}
if (components.length > 4) {
components[4].setBounds(x, 0, DATE_WIDTH, height);
}
}
}
/**
* JTree spécialisé pour l'explorateur de fichiers.
*/
class FileExplorerTree extends JTree {
private final Set<File> selectedFiles;
public FileExplorerTree(DefaultTreeModel model, Set<File> selectedFiles) {
super(model);
this.selectedFiles = selectedFiles;
setCellRenderer(new CheckBoxTreeCellRenderer());
setRootVisible(true);
setShowsRootHandles(true);
setRowHeight(24);
/*
* Gestion des clics.
*/
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
TreePath path = getPathForLocation(e.getX(), e.getY());
if (path == null) {
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
Object userObject = node.getUserObject();
if (!(userObject instanceof FileNode)) {
return;
}
FileNode fileNode = (FileNode) userObject;
/*
* Double-clic :
* uniquement pour naviguer dans les dossiers.
*/
if (e.getClickCount() == 2
&& e.getButton() == MouseEvent.BUTTON1) {
if (fileNode.isDirectory()) {
firePropertyChange(
"directoryDoubleClicked",
null,
fileNode.getFile()
);
}
return;
}
/*
* Simple clic :
* uniquement sur les fichiers.
*/
if (e.getClickCount() == 1
&& e.getButton() == MouseEvent.BUTTON1) {
if (fileNode.isFile()) {
toggleFile(fileNode.getFile());
repaint();
firePropertyChange("selectionChanged", null, fileNode.getFile());
}
else {
//if (path.getPathCount() == 1) { // simple clic sur la racine
if (node == (DefaultMutableTreeNode) getModel().getRoot()) {
boolean select = !areAllFilesSelected();
toggleAllFiles(select);
}
}
}
}
});
setupKeyboardActions(); // gestion du clavier
}
private void setupKeyboardActions() {
InputMap inputMap = getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "toggleFile");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "toggleFile");
actionMap.put("toggleFile", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath path = getSelectionPath();
if (path == null) {
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
Object userObject = node.getUserObject();
if (!(userObject instanceof FileNode)) {
return;
}
FileNode fileNode = (FileNode) userObject;
/*
* On ne permet de cocher/décocher que les fichiers, pas les dossiers.
*/
if (fileNode.isFile()) {
toggleFile(fileNode.getFile());
repaint();
firePropertyChange("selectionChanged", null, fileNode.getFile());
}
else {
//if (path.getPathCount() == 1) { // simple clic sur la racine
if (node == (DefaultMutableTreeNode) getModel().getRoot()) {
boolean select = !areAllFilesSelected();
toggleAllFiles(select);
}
}
}
});
}
public boolean areAllFilesSelected() {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getModel().getRoot();
return areAllFilesSelected(root);
}
private boolean areAllFilesSelected(DefaultMutableTreeNode node) {
boolean FilesIsSelected = false;
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
Object userObject = child.getUserObject();
if (userObject instanceof FileNode) {
FileNode fileNode = (FileNode) userObject;
if (fileNode.isFile()) {
if (!selectedFiles.contains(fileNode.getFile())) {
return false;
}
else {
FilesIsSelected = true;
}
}
}
//if (!areAllFilesSelected(child)) {
// return false;
//}
}
return FilesIsSelected;
}
private void toggleAllFiles(boolean select) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getModel().getRoot();
toggleFilesRecursively(root, select);
repaint();
firePropertyChange("selectionChanged", null, null);
}
private void toggleFilesRecursively(DefaultMutableTreeNode node, boolean select) {
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child =
(DefaultMutableTreeNode) node.getChildAt(i);
Object userObject = child.getUserObject();
if (userObject instanceof FileNode) {
FileNode fileNode = (FileNode) userObject;
if (fileNode.isFile()) {
if (select) {
selectedFiles.add(fileNode.getFile());
} else {
selectedFiles.remove(fileNode.getFile());
}
}
}
// On continue à parcourir les sous-dossiers.
toggleFilesRecursively(child, select);
}
}
private void toggleFile(File file) {
if (selectedFiles.contains(file)) {
selectedFiles.remove(file);
} else {
selectedFiles.add(file);
}
}
public boolean isFileSelected(File file) {
return selectedFiles.contains(file);
}
}
/**
* Application principale.
*/
public class CheckBoxTree extends JFrame {
private final JTextArea textArea;
private final JTextField textPath;
private final JLabel statusBar;
private final Set<File> selectedFiles;
private File currentDirectory;
private FileExplorerTree tree;
private DefaultTreeModel treeModel;
private static String fileSeparator = FileSystems.getDefault().getSeparator();
public CheckBoxTree() {
/*
* ============================
* Initialisation
* ============================
*/
selectedFiles = new LinkedHashSet<File>();
//currentDirectory = new File(".").getAbsoluteFile();
currentDirectory = new File(System.getProperty("user.dir")).getAbsoluteFile();
/*
* ============================
* Fenêtre
* ============================
*/
setTitle("My file explorer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
/*
* ============================
* Menu
* ============================
*/
createMenuBar();
/*
* ============================
* Zone supérieure
* ============================
*/
JPanel panelZoneCentrale = new JPanel(new BorderLayout());
panelZoneCentrale.setPreferredSize(new Dimension(800, 150));
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane textScrollPane = new JScrollPane(textArea);
panelZoneCentrale.add(textScrollPane, BorderLayout.CENTER);
JButton buttonAction = new JButton("Action");
buttonAction.addActionListener(e -> executerAction());
panelZoneCentrale.add(buttonAction, BorderLayout.EAST);
add(panelZoneCentrale, BorderLayout.NORTH);
/*
* ============================
* Arbre
* ============================
*/
tree = createTree();
JScrollPane treeScrollPane = new JScrollPane(tree);
// Bandeau supérieur avec une bordure en haut et bas
JPanel panelCenter = new JPanel(new BorderLayout());
JPanel panelPath = new JPanel(new BorderLayout());
panelPath.setPreferredSize(new Dimension(600, 40));
panelPath.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); //top, left, bottom, right
textPath = new JTextField();
textPath.setEditable(false);
// Change text font size
textPath.setFont(new Font("SansSerif",Font.PLAIN,14)); //(new Font("Serif",Font.BOLD,12));
// Change text font color
textPath.setBackground(Color.WHITE);
textPath.setForeground(Color.BLACK);
panelPath.add(textPath, BorderLayout.CENTER);
JButton buttonOpen = new JButton("Open");
buttonOpen.addActionListener(e -> executerOpen());
JPanel panelButton = new JPanel(new BorderLayout());
// Ajoute un espace entre textPath et buttonOpen
panelButton.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
panelButton.add(buttonOpen, BorderLayout.CENTER);
panelPath.add(panelButton,BorderLayout.EAST);
panelCenter.add(panelPath, BorderLayout.NORTH);
panelCenter.add(treeScrollPane, BorderLayout.CENTER);
// Ajoute ces panels à la frame principale
add(panelCenter, BorderLayout.CENTER);
/*
* ============================
* Barre de statut
* ============================
*/
statusBar = new JLabel();
statusBar.setHorizontalAlignment(SwingConstants.LEFT);
statusBar.setBorder(BorderFactory.createEtchedBorder());
add(statusBar, BorderLayout.SOUTH);
/*
* Chargement initial.
*/
loadDirectory(currentDirectory);
/*
* ============================
* Fenêtre
* ============================
*/
setSize(800, 800);
//setPreferredSize(new Dimension(800, 800));
setLocationRelativeTo(null);
}
/**
* Création de l'arbre.
*/
private FileExplorerTree createTree() {
DefaultMutableTreeNode root =
new DefaultMutableTreeNode(
new FileNode(
currentDirectory,
FileNodeType.DIRECTORY
)
);
treeModel =
new DefaultTreeModel(root);
FileExplorerTree fileTree =
new FileExplorerTree(
treeModel,
selectedFiles
);
fileTree.addPropertyChangeListener(
"directoryDoubleClicked",
evt -> {
File directory =
(File) evt.getNewValue();
loadDirectory(directory);
}
);
fileTree.addPropertyChangeListener(
"selectionChanged",
evt -> updateStatusBar()
);
return fileTree;
}
private static String stripLeadingZeros(String value) {
int i = 0;
while (i < value.length() - 1 && value.charAt(i) == '0') {
i++;
}
return value.substring(i);
}
private static int naturalCompare(String s1, String s2, Collator collator) {
int i = 0;
int j = 0;
while (i < s1.length() && j < s2.length()) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(j);
// Les deux caractères commencent un nombre
if (Character.isDigit(c1) && Character.isDigit(c2)) {
int start1 = i;
int start2 = j;
// Cherche la fin du nombre
while (i < s1.length()
&& Character.isDigit(s1.charAt(i))) {
i++;
}
while (j < s2.length()
&& Character.isDigit(s2.charAt(j))) {
j++;
}
String num1 = s1.substring(start1, i);
String num2 = s2.substring(start2, j);
// Supprime les zéros à gauche
//String n1 = num1.replaceFirst("^0+(?!$)", "");
//String n2 = num2.replaceFirst("^0+(?!$)", "");
String n1 = stripLeadingZeros(num1);
String n2 = stripLeadingZeros(num2);
// Compare d'abord la longueur :
// 2 chiffres < 10 chiffres
if (n1.length() != n2.length()) {
return n1.length() < n2.length() ? -1 : 1;
}
// Même longueur : comparaison lexicographique
int result = n1.compareTo(n2);
if (result != 0) {
return result;
}
// Même valeur numérique.
// On peut départager "001" et "1".
if (num1.length() != num2.length()) {
return num1.length() < num2.length() ? -1 : 1;
}
continue;
}
// Comparaison de la partie non numérique
int start1 = i;
int start2 = j;
while (i < s1.length()
&& !Character.isDigit(s1.charAt(i))) {
i++;
}
while (j < s2.length()
&& !Character.isDigit(s2.charAt(j))) {
j++;
}
String part1 = s1.substring(start1, i);
String part2 = s2.substring(start2, j);
int result = collator.compare(part1, part2);
if (result != 0) {
return result;
}
}
// Si tout ce qui précède est identique,
// le plus court vient en premier.
if (i < s1.length()) {
return 1;
}
if (j < s2.length()) {
return -1;
}
return 0;
}
/**
* Charge le contenu d'un répertoire.
*/
private void loadDirectory(File directory) {
if (directory == null) {
return;
}
if (!directory.isDirectory()) {
return;
}
/*
* La navigation réinitialise la sélection.
*/
selectedFiles.clear();
currentDirectory = directory.getAbsoluteFile();
/*
* Nouveau modèle.
*/
DefaultMutableTreeNode root =
new DefaultMutableTreeNode(
new FileNode(
currentDirectory,
FileNodeType.DIRECTORY
)
);
/*
* ============================
* Répertoire parent
* ============================
*/
File parent =
currentDirectory.getParentFile();
if (parent != null) {
root.add(
new DefaultMutableTreeNode(
new FileNode(
parent,
FileNodeType.PARENT_DIRECTORY
)
)
);
}
/*
* ============================
* Contenu du répertoire
* ============================
*/
Collator collator = Collator.getInstance(Locale.FRENCH);
collator.setStrength(Collator.PRIMARY);
File[] files = currentDirectory.listFiles();
if (files != null) {
/*
* Sort by :
* 1. directories
* 2. files
* 3. filenames with "natural sort"
*/
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
// 1. Directories before files
boolean dir1 = f1.isDirectory();
boolean dir2 = f2.isDirectory();
if (dir1 && !dir2) {
return -1;
}
if (!dir1 && dir2) {
return 1;
}
// 2. "natural sort" method
return naturalCompare(f1.getName(), f2.getName(),collator);
//return f1.getName().compareToIgnoreCase(f2.getName()); // old method
}
});
//Arrays.sort(files, WindowsFileComparator.INSTANCE);
for (File file : files) {
FileNodeType type;
if (file.isDirectory()) {
type =
FileNodeType.DIRECTORY;
} else {
type =
FileNodeType.FILE;
}
root.add(
new DefaultMutableTreeNode(
new FileNode(
file,
type
)
)
);
}
}
/*
* Remplacement du modèle.
*/
treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
/*
* Mise à jour du titre.
*/
//setTitle("My file explorer - " + currentDirectory.getAbsolutePath());
setTitle("My file explorer - [" + currentDirectory.getName() + "]");
String str1 = currentDirectory.getAbsolutePath();
if (!str1.isEmpty()) {
if (!(fileSeparator.equals(str1.substring(str1.length() - 1))))
str1 = str1 + fileSeparator;
}
else str1 = "." + fileSeparator;
textPath.setText(str1);
updateStatusBar();
}
/**
* Mise à jour de la barre de statut.
*/
private void updateStatusBar() {
int count =
selectedFiles.size();
if (count == 0) {
statusBar.setText(
"No file selected"
);
} else if (count == 1) {
statusBar.setText(