-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXmlAppGUI.java
More file actions
1528 lines (1322 loc) · 72.4 KB
/
Copy pathXmlAppGUI.java
File metadata and controls
1528 lines (1322 loc) · 72.4 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 java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;
import javax.xml.stream.XMLStreamException;
import java.lang.Exception;
import java.awt.Desktop;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.Timer;
import java.awt.Color;
public class XmlAppGUI {
// Dark mode colors
private static final Color DARK_BACKGROUND = new Color(45, 45, 45);
private static final Color DARK_PANEL = new Color(60, 60, 60);
private static final Color DARK_TEXT = new Color(220, 220, 220);
private static final Color DARK_BORDER = new Color(80, 80, 80);
private static final Color LIGHT_BACKGROUND = Color.WHITE;
private static final Color LIGHT_PANEL = new Color(240, 240, 240);
private static final Color LIGHT_TEXT = Color.BLACK;
private static boolean isDarkMode = false;
private static boolean useAutoNaming = true; // Controls automatic output file naming
private static boolean useDefaultOutputPath = true; // Controls using default output path (same as input)
private static volatile boolean isCanceled = false; // Flag for canceling operations
private static boolean showDetailedView = false; // Controls detailed file properties view
private static boolean enableCSVExport = false; // Controls CSV export instead of Excel
/**
* Formats file size in human readable format
*/
private static String formatFileSize(long bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
if (bytes < 1024 * 1024 * 1024) return String.format("%.1f MB", bytes / (1024.0 * 1024.0));
return String.format("%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
}
/**
* Formats date in readable format
*/
private static String formatDate(long timestamp) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd, yyyy HH:mm");
return sdf.format(new java.util.Date(timestamp));
}
/**
* Gets basic file type info
*/
private static String getFileInfo(File file) {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith(".xml")) {
return "XML Document";
} else if (fileName.endsWith(".xlsx")) {
return "Excel Workbook";
} else if (fileName.endsWith(".csv")) {
return "CSV File";
} else {
return "Unknown Type";
}
}
private static String createErrorMessage(Throwable ex) {
String message = ex.getMessage().toLowerCase();
if (ex instanceof InterruptedException) {
return "The process is cancelled.";
}
if (ex instanceof FileNotFoundException || message.contains("file not found")) {
return "The selected file could not be found. It may have been moved or deleted.";
}
if (ex instanceof XMLStreamException || message.contains("xml") || message.contains("parse")) {
return "The file is not a valid XML file or corrupted.";
}
if (message.contains("access") || message.contains("permission")) {
return "Cannot access the file. Please check file permissions.";
}
if (message.contains("memory") || message.contains("heap")) {
return "The file is too large to process. Try processing smaller files.";
}
return "An unexpected error occurred while processing the file.";
}
/**
* Applies theme to all components
*/
private static void applyTheme(JFrame frame, JPanel filePanel, JPanel buttonPanel, JPanel listsPanel,
JList<File> inputList, JList<File> outputList,
JPanel statusPanel, JLabel statusBarLabel, JLabel fileCountLabel,
JButton... buttons) {
Color bgColor = isDarkMode ? DARK_BACKGROUND : LIGHT_BACKGROUND;
Color panelColor = isDarkMode ? DARK_PANEL : LIGHT_PANEL;
Color textColor = isDarkMode ? DARK_TEXT : LIGHT_TEXT;
// Frame
frame.getContentPane().setBackground(bgColor);
// Panels
filePanel.setBackground(panelColor);
buttonPanel.setBackground(panelColor);
listsPanel.setBackground(panelColor);
// Status bar components
if (statusPanel != null) {
statusPanel.setBackground(panelColor);
}
if (statusBarLabel != null) {
statusBarLabel.setForeground(textColor);
}
if (fileCountLabel != null) {
fileCountLabel.setForeground(textColor);
}
// Lists
inputList.setBackground(panelColor);
inputList.setForeground(textColor);
outputList.setBackground(panelColor);
outputList.setForeground(textColor);
// Apply theme to all labels in the frame
applyThemeToLabels(frame, textColor);
// Buttons
for (JButton button : buttons) {
button.setBackground(isDarkMode ? DARK_BORDER : Color.LIGHT_GRAY);
button.setForeground(textColor);
}
// Menu bar
JMenuBar menuBar = frame.getJMenuBar();
if (menuBar != null) {
menuBar.setBackground(panelColor);
applyThemeToMenuBar(menuBar, textColor, panelColor);
}
frame.repaint();
}
/**
* Recursively applies theme to all labels in a container
*/
private static void applyThemeToLabels(java.awt.Container container, Color textColor) {
for (java.awt.Component comp : container.getComponents()) {
if (comp instanceof JLabel) {
comp.setForeground(textColor);
} else if (comp instanceof java.awt.Container) {
applyThemeToLabels((java.awt.Container) comp, textColor);
}
}
}
/**
* Applies theme to menu bar
* @param menuBar
* @param textColor text color
* @param bgColor background color
*/
private static void applyThemeToMenuBar(JMenuBar menuBar, Color textColor, Color bgColor) {
menuBar.setBackground(bgColor);
for (int i = 0; i < menuBar.getMenuCount(); i++) {
JMenu menu = menuBar.getMenu(i);
menu.setForeground(textColor);
menu.setBackground(bgColor);
for (int j = 0; j < menu.getItemCount(); j++) {
JMenuItem item = menu.getItem(j);
if (item != null) {
item.setForeground(textColor);
item.setBackground(bgColor);
}
}
}
}
/**
* Creates GUI for XML processing application
* @param isCSV output file type checker
*/
public static void createFrame(boolean isCSV) {
// Note: isCSV parameter is now controlled by enableCSVExport checkbox in Options menu
JFrame frame = new JFrame("XML Parser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 650); // Reduced height for smaller screens
frame.setResizable(true); // Made resizable for better user experience
frame.setMinimumSize(new java.awt.Dimension(800, 500)); // Reduced minimum size
// File chooser with xml filter
JFileChooser fileChooser = new JFileChooser("C:\\Users\\ebubekir.siddik\\Desktop");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", new String[] {"xml", "XML"});
fileChooser.setFileFilter(filter);
fileChooser.addChoosableFileFilter(filter);
// Selected file display
JLabel selectedFileLabel = new JLabel("No file selected");
// For input XML files
DefaultListModel<File> inputFilesModel = new DefaultListModel<>();
JList<File> inputFilesList = new JList<>(inputFilesModel);
inputFilesList.setFixedCellHeight(showDetailedView ? 75 : 50); // Dynamic height based on view mode
// Custom cell renderer to show file details
inputFilesList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public java.awt.Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof File) {
File file = (File) value;
String fileName = file.getName();
String folderPath = file.getParent();
// Shorten very long paths for display
if (folderPath != null && folderPath.length() > 50) {
folderPath = "..." + folderPath.substring(folderPath.length() - 47);
}
if (showDetailedView) {
// Detailed view with file properties
String fileSize = formatFileSize(file.length());
String lastModified = formatDate(file.lastModified());
String fileInfo = getFileInfo(file);
String displayText = "<html><b>" + fileName + "</b><br>" +
"<small style='color: gray;'>📁 " + (folderPath != null ? folderPath : "Unknown") + "</small><br>" +
"<small style='color: blue;'>📊 " + fileSize + " • 🕒 " + lastModified + " • " + fileInfo + "</small></html>";
setText(displayText);
} else {
// Simple view (original)
String displayText = "<html><b>" + fileName + "</b><br>" +
"<small style='color: gray;'>📁 " + (folderPath != null ? folderPath : "Unknown") + "</small></html>";
setText(displayText);
}
}
// Add padding and separator border
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), // Bottom separator line
BorderFactory.createEmptyBorder(showDetailedView ? 15 : 12, 15, showDetailedView ? 15 : 12, 15) // Dynamic padding
));
return this;
}
});
// Double click to open the file (replaced by new mouse listener below)
// For output Excel/CSV files
DefaultListModel<File> outputFilesModel = new DefaultListModel<>();
JList<File> outputFilesList = new JList<>(outputFilesModel);
outputFilesList.setFixedCellHeight(showDetailedView ? 75 : 50); // Dynamic height based on view mode
// Custom cell renderer to show file details
outputFilesList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public java.awt.Component getListCellRendererComponent(JList<?> list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof File) {
File file = (File) value;
String fileName = file.getName();
String folderPath = file.getParent();
// Shorten very long paths for display
if (folderPath != null && folderPath.length() > 50) {
folderPath = "..." + folderPath.substring(folderPath.length() - 47);
}
if (showDetailedView) {
// Detailed view with file properties
String fileSize = file.exists() ? formatFileSize(file.length()) : "Not found";
String lastModified = file.exists() ? formatDate(file.lastModified()) : "Unknown";
String fileType = getFileInfo(file); // Use the same method as input files
String displayText = "<html><b>" + fileName + "</b><br>" +
"<small style='color: gray;'>📁 " + (folderPath != null ? folderPath : "Unknown") + "</small><br>" +
"<small style='color: green;'>📊 " + fileSize + " • 🕒 " + lastModified + " • " + fileType + "</small></html>";
setText(displayText);
} else {
// Simple view (original)
String displayText = "<html><b>" + fileName + "</b><br>" +
"<small style='color: gray;'>📁 " + (folderPath != null ? folderPath : "Unknown") + "</small></html>";
setText(displayText);
}
}
// Add padding and separator border
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), // Bottom separator line
BorderFactory.createEmptyBorder(showDetailedView ? 15 : 12, 15, showDetailedView ? 15 : 12, 15) // Dynamic padding
));
return this;
}
});
// Add mutual exclusion between input and output list selections
// Update input list selection listener
inputFilesList.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
File selectedFile = inputFilesList.getSelectedValue();
if (selectedFile != null) {
selectedFileLabel.setText("Selected: " + selectedFile.getName());
// Clear output list selection when input is selected
outputFilesList.clearSelection();
} else {
selectedFileLabel.setText("No file selected");
}
}
});
// Add selection listener for output list
outputFilesList.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
File selectedFile = outputFilesList.getSelectedValue();
if (selectedFile != null) {
selectedFileLabel.setText("Selected Output: " + selectedFile.getName());
// Clear input list selection when output is selected
inputFilesList.clearSelection();
} else {
selectedFileLabel.setText("No file selected");
}
}
});
// Add click-to-unselect functionality for both lists
inputFilesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int index = inputFilesList.locationToIndex(e.getPoint());
if (e.getButton() == MouseEvent.BUTTON3) { // Right click
// Select the item under cursor for context menu
if (index >= 0 && inputFilesList.getCellBounds(index, index).contains(e.getPoint())) {
inputFilesList.setSelectedIndex(index);
showInputFileContextMenu(e, inputFilesList, inputFilesModel, frame);
} else {
// Right click on empty space - show general context menu
showInputListContextMenu(e, inputFilesList, inputFilesModel, frame, fileChooser);
}
return;
}
if (e.getClickCount() == 1) {
// Single click: check if clicked on empty space
if (index == -1 || !inputFilesList.getCellBounds(index, index).contains(e.getPoint())) {
// Clicked on empty space, unselect
inputFilesList.clearSelection();
selectedFileLabel.setText("No file selected");
}
// If clicked on an item, normal selection behavior will handle it
} else if (e.getClickCount() == 2) {
// Double click: open file
if (index >= 0) {
File selectedFile = inputFilesList.getModel().getElementAt(index);
if (selectedFile != null && selectedFile.exists()) {
try {
Desktop.getDesktop().open(selectedFile);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Could not open file: " + createErrorMessage(ex), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
});
outputFilesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int index = outputFilesList.locationToIndex(e.getPoint());
if (e.getButton() == MouseEvent.BUTTON3) { // Right click
// Select the item under cursor for context menu
if (index >= 0 && outputFilesList.getCellBounds(index, index).contains(e.getPoint())) {
outputFilesList.setSelectedIndex(index);
showOutputFileContextMenu(e, outputFilesList, outputFilesModel, frame);
} else {
// Right click on empty space - show general context menu
showOutputListContextMenu(e, outputFilesList, outputFilesModel, frame);
}
return;
}
if (e.getClickCount() == 1) {
// Single click: check if clicked on empty space
if (index == -1 || !outputFilesList.getCellBounds(index, index).contains(e.getPoint())) {
// Clicked on empty space, unselect
outputFilesList.clearSelection();
selectedFileLabel.setText("No file selected");
}
// If clicked on an item, normal selection behavior will handle it
} else if (e.getClickCount() == 2) {
// Double click: open file
if (index >= 0) {
File selectedFile = outputFilesList.getModel().getElementAt(index);
if (selectedFile != null && selectedFile.exists()) {
try {
Desktop.getDesktop().open(selectedFile);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Could not open file: " + createErrorMessage(ex), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
});
// Add DEL key support for input files
inputFilesList.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
File selectedFile = inputFilesList.getSelectedValue();
if (selectedFile != null) {
deleteSelectedFile(selectedFile, inputFilesModel, frame, "input");
}
}
}
});
// Add DEL key support for output files
outputFilesList.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
File selectedFile = outputFilesList.getSelectedValue();
if (selectedFile != null) {
deleteSelectedFile(selectedFile, outputFilesModel, frame, "output");
}
}
}
});
// Select File button
JButton loadFileButton = new JButton("Load File");
loadFileButton.addActionListener(e -> {
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
inputFilesModel.addElement(fileChooser.getSelectedFile());
}
});
// Process File button
JButton processButton = new JButton("Process File");
processButton.addActionListener(e -> {
File selectedFileFromList = inputFilesList.getSelectedValue();
if (selectedFileFromList == null) {
JOptionPane.showMessageDialog(frame, "Please select a file from the list first!", "No File Selected", JOptionPane.WARNING_MESSAGE);
return;
}
// Optional: warn for very large files (>50MB)
if (selectedFileFromList.length() > 50 * 1024 * 1024) {
int choice = JOptionPane.showConfirmDialog(frame,
"This file is quite large (" + (selectedFileFromList.length() / (1024 * 1024)) + " MB). Processing may take some time. Continue?",
"Large File Warning", JOptionPane.YES_NO_OPTION);
if (choice != JOptionPane.YES_OPTION) return;
}
// Handle output path selection if default path is disabled
final File outputDirectory;
if (!useDefaultOutputPath) {
JFileChooser outputFolderChooser = new JFileChooser();
outputFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
outputFolderChooser.setDialogTitle("Select Output Folder");
outputFolderChooser.setCurrentDirectory(selectedFileFromList.getParentFile()); // Start from input file location
int result = outputFolderChooser.showSaveDialog(frame);
if (result != JFileChooser.APPROVE_OPTION) {
return; // User canceled folder selection
}
outputDirectory = outputFolderChooser.getSelectedFile();
} else {
outputDirectory = null; // Use default path
}
// Create progress dialog
JDialog progressDialog = new JDialog(frame, "Processing File", true);
progressDialog.setSize(400, 180);
progressDialog.setLocationRelativeTo(frame);
progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
JPanel progressPanel = new JPanel(new BorderLayout(10, 10));
progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel progressLabel = new JLabel("Processing: " + selectedFileFromList.getName());
progressLabel.setHorizontalAlignment(SwingConstants.CENTER);
progressLabel.setFont(progressLabel.getFont().deriveFont(java.awt.Font.BOLD, 14f)); // Make title bold and larger
JLabel statusLabel = new JLabel("Preparing to process...");
statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
statusLabel.setFont(statusLabel.getFont().deriveFont(12f));
// Add separator between title and status
JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
separator.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
progressBar.setStringPainted(false); // Don't show text inside the bar
// Create a panel for status and progress bar
JPanel progressSubPanel = new JPanel(new BorderLayout(5, 5));
progressSubPanel.add(statusLabel, BorderLayout.NORTH);
progressSubPanel.add(progressBar, BorderLayout.CENTER);
// Create a panel for title and separator
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.add(progressLabel, BorderLayout.NORTH);
titlePanel.add(separator, BorderLayout.SOUTH);
// Reset cancel flag
isCanceled = false;
// Declare worker variable to be accessible in cancel button
@SuppressWarnings("unchecked")
final SwingWorker<XmlParser, String>[] workerRef = new SwingWorker[1];
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(cancelEvent -> {
isCanceled = true;
if (workerRef[0] != null && !workerRef[0].isDone()) {
workerRef[0].cancel(true);
}
progressDialog.dispose();
});
progressPanel.add(titlePanel, BorderLayout.NORTH);
progressPanel.add(progressSubPanel, BorderLayout.CENTER);
progressPanel.add(cancelButton, BorderLayout.SOUTH);
progressDialog.add(progressPanel);
// Process file in background thread
SwingWorker<XmlParser, String> worker = new SwingWorker<XmlParser, String>() {
private XmlParser parser;
@Override
protected XmlParser doInBackground() throws Exception {
try {
publish("Initializing parser...");
if (useDefaultOutputPath) {
// Use default path (same as input file location)
if (useAutoNaming) {
parser = new XmlParser(selectedFileFromList.toPath(), enableCSVExport);
} else {
// For manual naming with default path, we'll use a simpler approach
parser = new XmlParser(selectedFileFromList.toPath(), enableCSVExport); // Fallback to auto naming for now
}
} else {
// Use custom output directory
String inputFileName = selectedFileFromList.getName();
String nameWithoutExtension = inputFileName.contains(".") ?
inputFileName.substring(0, inputFileName.lastIndexOf('.')) : inputFileName;
String outputFileName = nameWithoutExtension + "_out." + (enableCSVExport ? "csv" : "xlsx");
java.nio.file.Path customOutputPath = outputDirectory.toPath().resolve(outputFileName);
parser = new XmlParser(selectedFileFromList.toPath(), customOutputPath, enableCSVExport);
}
if (isCanceled) {
parser.cancel();
return null;
}
publish("Processing XML data...");
parser.processFile();
if (isCanceled) {
parser.cancel();
return null;
}
publish("Finalizing output...");
return parser;
} catch (Exception ex) {
throw ex;
}
}
@Override
protected void process(java.util.List<String> chunks) {
if (!chunks.isEmpty()) {
statusLabel.setText(chunks.get(chunks.size() - 1));
}
}
@Override
protected void done() {
progressDialog.dispose();
if (isCanceled) {
JOptionPane.showMessageDialog(frame, "Operation canceled by user.", "Canceled", JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
XmlParser result = get();
if (result != null) {
// Add to output list
File processedFile = result.getOutputPath().toFile();
if (outputFilesModel.contains(processedFile)) {
outputFilesModel.removeElement(processedFile);
}
outputFilesModel.addElement(processedFile);
JOptionPane.showMessageDialog(frame, "File processed successfully!\nOutput: " + result.getOutputPath().getFileName(), "Success", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception ex) {
// Create custom dialog with "Remove from List" option
String errorMessage = "Error processing file: " + createErrorMessage(ex);
String[] options = {"Remove from List", "OK"};
int choice = JOptionPane.showOptionDialog(frame,
errorMessage,
"Error",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[1]);
if (choice == 0) { // "Remove from List" was selected
inputFilesModel.removeElement(selectedFileFromList);
showTemporaryMessage(frame, "File removed from input list", "Removed");
}
}
}
};
workerRef[0] = worker;
worker.execute();
progressDialog.setVisible(true);
});
JButton openLastButton = new JButton("Open Last Output");
openLastButton.addActionListener(e -> {
if (!outputFilesModel.isEmpty()) {
try {
File lastFile = outputFilesModel.getElementAt(outputFilesModel.getSize() - 1);
Desktop.getDesktop().open(lastFile);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error opening file: " + createErrorMessage(ex), "Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(frame, "No files created yet", "No Files", JOptionPane.WARNING_MESSAGE);
}
});
JButton deleteAllButton = new JButton("Delete All");
deleteAllButton.addActionListener(e -> {
boolean hasInputFiles = !inputFilesModel.isEmpty();
boolean hasOutputFiles = !outputFilesModel.isEmpty();
if (!hasInputFiles && !hasOutputFiles) {
JOptionPane.showMessageDialog(frame, "No files to delete.", "No Files", JOptionPane.INFORMATION_MESSAGE);
return;
}
String message = "Delete all files from both lists?\n\n";
if (hasInputFiles) {
message += "• " + inputFilesModel.size() + " input file(s)\n";
}
if (hasOutputFiles) {
message += "• " + outputFilesModel.size() + " output file(s)\n";
}
message += "\nThis will remove files from disk permanently!";
int confirm = JOptionPane.showConfirmDialog(frame, message,
"Confirm Delete All", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
int deletedCount = 0;
int failedCount = 0;
// Delete input files
for (int i = inputFilesModel.size() - 1; i >= 0; i--) {
File file = inputFilesModel.getElementAt(i);
if (file.delete()) {
inputFilesModel.removeElementAt(i);
deletedCount++;
} else {
failedCount++;
}
}
// Delete output files
for (int i = outputFilesModel.size() - 1; i >= 0; i--) {
File file = outputFilesModel.getElementAt(i);
if (file.delete()) {
outputFilesModel.removeElementAt(i);
deletedCount++;
} else {
failedCount++;
}
}
// Show result
String resultMessage = deletedCount + " file(s) deleted successfully.";
if (failedCount > 0) {
resultMessage += "\n" + failedCount + " file(s) could not be deleted.";
}
JOptionPane.showMessageDialog(frame, resultMessage, "Delete Complete",
failedCount > 0 ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE);
}
});
// Name of the selected file panel and its design
JPanel filePanel = new JPanel();
filePanel.setLayout(new GridLayout(0, 1));
filePanel.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(8, 8, 8, 8), // Reduced outer margin
BorderFactory.createCompoundBorder(
BorderFactory.createEtchedBorder(EtchedBorder.RAISED), // Visible border
BorderFactory.createEmptyBorder(8, 12, 8, 12) // Reduced inner padding
)
)
);
filePanel.add(selectedFileLabel);
// Panel for buttons and their design
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 4, 10, 0)); // 1 row, 4 columns, 10px horizontal gap
buttonPanel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12)); // Reduced padding
buttonPanel.add(loadFileButton);
buttonPanel.add(processButton);
buttonPanel.add(openLastButton);
buttonPanel.add(deleteAllButton);
// input-output lists
JPanel listsPanel = new JPanel();
listsPanel.setLayout(new GridLayout(1, 2, 10, 0)); // 1 row, 2 columns, 10px gap
// Wrap JLists in JScrollPanes for scrolling
JScrollPane inputScrollPane = new JScrollPane(inputFilesList);
inputScrollPane.setBorder(BorderFactory.createTitledBorder("Input XML Files"));
JScrollPane outputScrollPane = new JScrollPane(outputFilesList);
outputScrollPane.setBorder(BorderFactory.createTitledBorder("Output Files"));
listsPanel.add(inputScrollPane);
listsPanel.add(outputScrollPane);
// Layout setup - Use BorderLayout for better control
frame.setLayout(new BorderLayout());
// Create status bar
JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY),
BorderFactory.createEmptyBorder(5, 10, 5, 10)
));
JLabel statusBarLabel = new JLabel("Ready");
JLabel fileCountLabel = new JLabel("Files: 0 input, 0 output");
statusPanel.add(statusBarLabel, BorderLayout.WEST);
statusPanel.add(fileCountLabel, BorderLayout.EAST);
// Create bottom panel that contains both buttons and status bar
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(buttonPanel, BorderLayout.NORTH); // Buttons on top
bottomPanel.add(statusPanel, BorderLayout.SOUTH); // Status bar below buttons
// Update file count when lists change
inputFilesModel.addListDataListener(new javax.swing.event.ListDataListener() {
public void intervalAdded(javax.swing.event.ListDataEvent e) { updateFileCount(); }
public void intervalRemoved(javax.swing.event.ListDataEvent e) { updateFileCount(); }
public void contentsChanged(javax.swing.event.ListDataEvent e) { updateFileCount(); }
private void updateFileCount() {
fileCountLabel.setText("Files: " + inputFilesModel.size() + " input, " + outputFilesModel.size() + " output");
}
});
outputFilesModel.addListDataListener(new javax.swing.event.ListDataListener() {
public void intervalAdded(javax.swing.event.ListDataEvent e) { updateFileCount(); }
public void intervalRemoved(javax.swing.event.ListDataEvent e) { updateFileCount(); }
public void contentsChanged(javax.swing.event.ListDataEvent e) { updateFileCount(); }
private void updateFileCount() {
fileCountLabel.setText("Files: " + inputFilesModel.size() + " input, " + outputFilesModel.size() + " output");
}
});
// Add components to frame
frame.setJMenuBar(createUpperMenu(frame, fileChooser, inputFilesModel, outputFilesModel,
filePanel, buttonPanel, listsPanel, inputFilesList, outputFilesList,
selectedFileLabel, statusPanel, statusBarLabel, fileCountLabel,
loadFileButton, processButton, openLastButton, deleteAllButton));
frame.add(filePanel, BorderLayout.NORTH); // Top - small fixed height
frame.add(listsPanel, BorderLayout.CENTER); // Middle - takes remaining space
frame.add(bottomPanel, BorderLayout.SOUTH); // Bottom - buttons + status bar
// Apply initial theme (including status bar)
applyTheme(frame, filePanel, buttonPanel, listsPanel, inputFilesList, outputFilesList,
statusPanel, statusBarLabel, fileCountLabel,
loadFileButton, processButton, openLastButton, deleteAllButton);
frame.setVisible(true);
}
/**
* Helper method to delete a selected file with confirmation
*/
private static void deleteSelectedFile(File file, DefaultListModel<File> model, JFrame frame, String listType) {
int confirm = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to delete this " + listType + " file from disk?\n" + file.getAbsolutePath(),
"Confirm Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
if (file.delete()) {
model.removeElement(file);
showTemporaryMessage(frame, "File deleted successfully.", "Deleted");
} else {
JOptionPane.showMessageDialog(frame, "Failed to delete file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Shows context menu for input file items
*/
private static void showInputFileContextMenu(MouseEvent e, JList<File> inputFilesList, DefaultListModel<File> inputFilesModel, JFrame frame) {
File selectedFile = inputFilesList.getSelectedValue();
if (selectedFile == null) return;
JPopupMenu contextMenu = new JPopupMenu();
// Open file
JMenuItem openItem = new JMenuItem("Open File");
openItem.addActionListener(event -> {
try {
Desktop.getDesktop().open(selectedFile);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Could not open file: " + createErrorMessage(ex), "Error", JOptionPane.ERROR_MESSAGE);
}
});
// Show in file explorer
JMenuItem showInExplorerItem = new JMenuItem("Show in File Explorer");
showInExplorerItem.addActionListener(event -> {
try {
Desktop.getDesktop().open(selectedFile.getParentFile());
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Could not open file explorer: " + createErrorMessage(ex), "Error", JOptionPane.ERROR_MESSAGE);
}
});
// Copy file path
JMenuItem copyPathItem = new JMenuItem("Copy File Path");
copyPathItem.addActionListener(event -> {
java.awt.datatransfer.StringSelection stringSelection = new java.awt.datatransfer.StringSelection(selectedFile.getAbsolutePath());
java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
showTemporaryMessage(frame, "File path copied to clipboard", "Copied");
});
// File properties
JMenuItem propertiesItem = new JMenuItem("Properties");
propertiesItem.addActionListener(event -> {
showFileProperties(selectedFile, frame);
});
// Rename file
JMenuItem renameItem = new JMenuItem("Rename File");
renameItem.addActionListener(event -> {
String currentName = selectedFile.getName();
String nameWithoutExtension = currentName.contains(".") ?
currentName.substring(0, currentName.lastIndexOf('.')) : currentName;
String extension = currentName.contains(".") ?
currentName.substring(currentName.lastIndexOf('.')) : "";
String newName = (String) JOptionPane.showInputDialog(frame,
"Enter new filename (without extension):",
"Rename File",
JOptionPane.PLAIN_MESSAGE,
null,
null,
nameWithoutExtension);
if (newName != null && !newName.trim().isEmpty() && !newName.equals(nameWithoutExtension)) {
newName = newName.trim() + extension;
File newFile = new File(selectedFile.getParent(), newName);
if (newFile.exists()) {
JOptionPane.showMessageDialog(frame,
"A file with that name already exists!",
"Rename Error",
JOptionPane.ERROR_MESSAGE);
} else if (selectedFile.renameTo(newFile)) {
// Update the model with the renamed file
int index = inputFilesModel.indexOf(selectedFile);
inputFilesModel.removeElement(selectedFile);
inputFilesModel.add(index, newFile);
inputFilesList.setSelectedValue(newFile, true);
showTemporaryMessage(frame, "File renamed successfully.", "Renamed");
} else {
JOptionPane.showMessageDialog(frame,
"Failed to rename file. Check file permissions.",
"Rename Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
// Remove from list
JMenuItem removeItem = new JMenuItem("Remove from List");
removeItem.addActionListener(event -> {
inputFilesModel.removeElement(selectedFile);
});
// Delete file
JMenuItem deleteItem = new JMenuItem("Delete File");
deleteItem.addActionListener(event -> {
int confirm = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to delete this file from disk?\n" + selectedFile.getAbsolutePath(),
"Confirm Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
if (selectedFile.delete()) {
inputFilesModel.removeElement(selectedFile);
showTemporaryMessage(frame, "File deleted successfully.", "Deleted");
} else {
JOptionPane.showMessageDialog(frame, "Failed to delete file.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
contextMenu.add(openItem);
contextMenu.add(showInExplorerItem);
contextMenu.addSeparator();
contextMenu.add(copyPathItem);
contextMenu.add(propertiesItem);
contextMenu.add(renameItem);
contextMenu.addSeparator();
contextMenu.add(removeItem);
contextMenu.add(deleteItem);
contextMenu.show(inputFilesList, e.getX(), e.getY());
}
/**
* Shows context menu for input list (empty space)
*/
private static void showInputListContextMenu(MouseEvent e, JList<File> inputFilesList, DefaultListModel<File> inputFilesModel, JFrame frame, JFileChooser fileChooser) {
JPopupMenu contextMenu = new JPopupMenu();
// Add files
JMenuItem addFilesItem = new JMenuItem("Add Files...");
addFilesItem.addActionListener(event -> {
fileChooser.setMultiSelectionEnabled(true);
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File[] selectedFiles = fileChooser.getSelectedFiles();
for (File file : selectedFiles) {
if (!inputFilesModel.contains(file)) {
inputFilesModel.addElement(file);
}
}
}
fileChooser.setMultiSelectionEnabled(false);
});
// Clear all
JMenuItem clearAllItem = new JMenuItem("Clear All Files");
clearAllItem.addActionListener(event -> {
if (!inputFilesModel.isEmpty()) {
int confirm = JOptionPane.showConfirmDialog(frame, "Clear all input files from list?", "Confirm Clear", JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
inputFilesModel.clear();
}
}
});
// Refresh list
JMenuItem refreshItem = new JMenuItem("Refresh List");
refreshItem.addActionListener(event -> {
inputFilesList.repaint();
});
contextMenu.add(addFilesItem);
if (!inputFilesModel.isEmpty()) {
contextMenu.addSeparator();
contextMenu.add(clearAllItem);
}
contextMenu.addSeparator();
contextMenu.add(refreshItem);
contextMenu.show(inputFilesList, e.getX(), e.getY());