public class EmuRunPanel extends JPanel {
private static final File STORAGE_FILE = new File(System.getProperty("user.home"), ".matrix_launcher_games.txt");
code
private final UI appUI;
private final DefaultListModel<GameEntry> gamesListModel = new DefaultListModel<>();
private final JList<GameEntry> gamesList;
private final JButton launchBtn;
private final JButton removeBtn;
private final JLabel messageLabel;
private final JPanel emptyStatePanel;
public EmuRunPanel(UI ui) {
this.appUI = ui;
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel gamesLabel = new JLabel("Available Games");
gamesLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
add(gamesLabel, BorderLayout.NORTH);
gamesList = new JList<>(gamesListModel);
gamesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
gamesList.setCellRenderer(new GameEntryCellRenderer());
JScrollPane scrollPane = new JScrollPane(gamesList);
emptyStatePanel = createEmptyStatePanel();
emptyStatePanel.setVisible(gamesListModel.isEmpty());
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
gamesListModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override public void intervalAdded(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void intervalRemoved(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void contentsChanged(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
});
updateEmptyStateVisibility();
enableFileDragAndDrop(this);
enableFileDragAndDrop(gamesList);
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
launchBtn = new JButton("Launch");
launchBtn.setEnabled(false);
launchBtn.addActionListener(e -> launchSelectedGame());
launchBtn.setBackground(new Color(0, 128, 0));
launchBtn.setForeground(Color.WHITE);
launchBtn.setOpaque(true);
launchBtn.setBorderPainted(false);
JButton addBtn = new JButton("Add Game");
addBtn.addActionListener(e -> addGame());
removeBtn = new JButton("Remove");
removeBtn.setEnabled(false);
removeBtn.addActionListener(e -> removeSelectedGame());
removeBtn.setBackground(new Color(200, 0, 0));
removeBtn.setForeground(Color.WHITE);
removeBtn.setOpaque(true);
removeBtn.setBorderPainted(false);
buttonsPanel.add(addBtn);
buttonsPanel.add(removeBtn);
buttonsPanel.add(launchBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
messageLabel = new JLabel(" ");
messageLabel.setForeground(Color.GRAY);
bottomPanel.add(messageLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
gamesList.addListSelectionListener(e -> updateButtons());
gamesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
launchSelectedGame();
}
}
});
loadGamesFromStorage();
}
private JPanel createEmptyStatePanel() {
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel iconLabel = new JLabel(new DragDropIcon(64, 64));
iconLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel textLabel = new JLabel("Drag and Drop or Select JAR to Launch");
textLabel.setFont(new Font("SansSerif", Font.BOLD, 22));
textLabel.setForeground(Color.GRAY);
textLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
textLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
panel.add(iconLabel);
panel.add(textLabel);
return panel;
}
private void updateEmptyStateVisibility() {
emptyStatePanel.setVisible(gamesListModel.isEmpty());
}
private void enableFileDragAndDrop(Component comp) {
new DropTarget(comp, new DropTargetListener() {
@Override public void dragEnter(DropTargetDragEvent dtde) {
if (canAcceptDrop(dtde)) dtde.acceptDrag(DnDConstants.ACTION_COPY);
else dtde.rejectDrag();
}
@Override public void dragOver(DropTargetDragEvent dtde) {}
@Override public void dropActionChanged(DropTargetDragEvent dtde) {}
@Override public void dragExit(DropTargetEvent dte) {}
@Override
public void drop(DropTargetDropEvent dtde) {
try {
if (canAcceptDrop(dtde)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
@SuppressWarnings("unchecked")
List<File> droppedFiles = (List<File>) dtde.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
int launchedCount = 0;
for (File f : droppedFiles) {
if (isJarFile(f)) {
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, f);
if (!containsFile(f)) {
gamesListModel.addElement(new GameEntry(f, 0));
saveGamesToStorage();
}
launchedCount++;
}
}
if (launchedCount > 0)
setMessage("Launched " + launchedCount + " game(s) by drag and drop.");
else
setMessage("No valid JAR files found in drop.");
dtde.dropComplete(true);
} else {
dtde.rejectDrop();
}
} catch (Exception ex) {
ex.printStackTrace();
setMessage("Error processing dropped files.");
dtde.dropComplete(false);
}
}
private boolean canAcceptDrop(DropTargetDragEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
private boolean canAcceptDrop(DropTargetDropEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
});
}
private boolean isJarFile(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
private void addGame() {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("JAR Files", "jar"));
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File jar = chooser.getSelectedFile();
if (!containsFile(jar)) {
gamesListModel.addElement(new GameEntry(jar, 0));
saveGamesToStorage();
setMessage("Added: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
} else {
setMessage("Game already in list: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
}
}
}
private void removeSelectedGame() {
int idx = gamesList.getSelectedIndex();
if (idx >= 0) {
GameEntry removed = gamesListModel.getElementAt(idx);
gamesListModel.remove(idx);
saveGamesToStorage();
setMessage("Removed: " + removed.getFile().getName());
}
}
private void launchSelectedGame() {
GameEntry selectedEntry = gamesList.getSelectedValue();
if (selectedEntry != null) {
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, selectedEntry.getFile());
setMessage("Launching: " + selectedEntry.getFile().getName());
// Update last played timestamp
selectedEntry.setLastPlayedTimestamp(System.currentTimeMillis());
saveGamesToStorage();
gamesList.repaint();
} else {
setMessage("No game selected to launch.");
}
}
private void updateButtons() {
boolean selected = gamesList.getSelectedIndex() >= 0;
launchBtn.setEnabled(selected);
removeBtn.setEnabled(selected);
}
private void setMessage(String message) {
messageLabel.setText(message);
}
private boolean containsFile(File file) {
for (int i = 0; i < gamesListModel.size(); i++) {
if (gamesListModel.get(i).getFile().equals(file)) {
return true;
}
}
return false;
}
private void saveGamesToStorage() {
try (PrintWriter pw = new PrintWriter(new FileWriter(STORAGE_FILE))) {
for (int i = 0; i < gamesListModel.size(); i++) {
GameEntry entry = gamesListModel.get(i);
pw.println(entry.getFile().getAbsolutePath() + "|" + entry.getLastPlayedTimestamp());
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to save games list.");
}
}
private void loadGamesFromStorage() {
if (!STORAGE_FILE.exists()) return;
try (BufferedReader br = new BufferedReader(new FileReader(STORAGE_FILE))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\\|");
File file = new File(parts[0]);
long ts = 0L;
if (parts.length > 1) {
try {
ts = Long.parseLong(parts[1]);
} catch (NumberFormatException ignored) {}
}
if (file.exists() && isJarFile(file)) {
GameEntry entry = new GameEntry(file, ts);
if (!containsFile(file)) {
gamesListModel.addElement(entry);
}
}
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to load saved games.");
}
}
private static class GameEntry {
private final File file;
private long lastPlayedTimestamp;
public GameEntry(File file, long lastPlayedTimestamp) {
this.file = file;
this.lastPlayedTimestamp = lastPlayedTimestamp;
}
public File getFile() {
return file;
}
public long getLastPlayedTimestamp() {
return lastPlayedTimestamp;
}
public void setLastPlayedTimestamp(long timestamp) {
this.lastPlayedTimestamp = timestamp;
}
@Override
public String toString() {
return file.getName();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
GameEntry that = (GameEntry) other;
return file.equals(that.file);
}
@Override
public int hashCode() {
return file.hashCode();
}
}
private class GameEntryCellRenderer extends DefaultListCellRenderer {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof GameEntry) {
GameEntry ge = (GameEntry) value;
File file = ge.getFile();
long sizeKb = (file.length() + 1023) / 1024; // rounded KB
String lastPlayedStr = ge.getLastPlayedTimestamp() > 0
? dateFormat.format(new Date(ge.getLastPlayedTimestamp()))
: "Never";
label.setText(String.format("<html>%s<br/><small>Size: %d KB | Last Played: %s</small></html>",
file.getName(), sizeKb, lastPlayedStr));
}
return label;
}
}
private static class DragDropIcon implements Icon {
private final int width;
private final int height;
public DragDropIcon(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.LIGHT_GRAY);
int centerX = x + width / 2;
int centerY = y + height / 2;
g2d.setStroke(new BasicStroke(6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
g2d.drawLine(centerX, y + 10, centerX, y + height - 20);
Polygon arrowHead = new Polygon();
arrowHead.addPoint(centerX - 15, y + height - 45);
arrowHead.addPoint(centerX + 15, y + height - 45);
arrowHead.addPoint(centerX, y + height - 10);
g2d.fill(arrowHead);
} finally {
g2d.dispose();
}
}
@Override
public int getIconWidth() {
return width;
}
@Override
public int getIconHeight() {
return height;
}
}
}
Assistant
The EmuRunPanel class you posted is a well-structured Swing panel for managing and launching JAR-based games with an emulator. It supports adding/removing games, drag-and-drop support for quick launching, and persistent storage of the game list with last played timestamps.
Here's a summary and some insights about what your code does:
Main Features
Game List Display:
Shows the list of games (JAR files), each with name, size (rounded KB), and last played timestamp ("Never" if not played yet).
Add Game:
Uses a JFileChooser filtered for .jar files; avoids duplicates.
Remove Game:
Removes the selected game from the list and storage.
Launch Game:
Launches the selected game using the chosen emulator (from UI instance) and updates the last played timestamp.
Drag-and-Drop Support:
You can drag one or more JAR files onto the panel or the list to launch those immediately, adding them to the list if not already present.
Persistent Storage:
Reads and writes the list of games (file path and timestamp) to a hidden text file in the user's home directory (.matrix_launcher_games.txt).
Empty State UI:
Shows a message and icon when no games are available.
Custom Cell Renderer:
Displays rich HTML-formatted info with file size and last played.
Code Highlights and Suggestions
Drag-and-Drop Handling:
The DropTargetListener correctly handles file drops. You use checks for whether dropped files are .jar and launch them immediately.
Note: You might want to run EmulatorLauncher.launch() in a separate thread if launching is blocking or slow.
Also consider updating the UI asynchronously or providing feedback if launch fails.
Equality in GameEntry: equals and hashCode are overriden based on the file, which is great for comparing entries and avoiding duplicates.
Storage File:
You write entries line by line as .
User
would you suggest any hotfixes which can make sure my app can be 100% cross platfor,
Assistant
Your current code is generally well-written and uses standard Java Swing APIs, which are mostly cross-platform. However, here are some targeted hotfixes and improvements to help ensure your app behaves reliably and consistently across all platforms (Windows, macOS, Linux):
1. File Path Handling: Use File Properly and Avoid Hardcoded Separators
Your current use of File to store paths is good, but when reading/writing to the storage text file, make sure:
You store and read forward slashes ("/") consistently or just store raw absolute paths.
Avoid manipulating file paths manually; rely on File APIs, which are platform-aware.
public class EmuRunPanel extends JPanel {
private static final File STORAGE_FILE = new File(System.getProperty("user.home"), ".matrix_launcher_games.txt");
code
Assistant
Here is your updated EmuRunPanel class with the suggested cross-platform hotfixes applied:
File I/O uses UTF-8 encoding explicitly.
File comparisons use canonical paths to handle symlinks and path variations.
Added canRead() checks where appropriate.
UI fonts use platform defaults.
Last-used directory for file chooser remembered between adds.
Button backgrounds adjusted conditionally to avoid macOS Aqua painting issues.
public static void launch(String emulatorName, File jarFile) {
String emulatorJarName;
switch (emulatorName.toLowerCase()) {
case "angelchip":
emulatorJarName = "angelchip.jar";
break;
case "microemulator":
default:
emulatorJarName = "microemulator.jar";
break;
}
File emulatorJar = new File("libs", emulatorJarName);
if (!emulatorJar.exists()) {
JOptionPane.showMessageDialog(null,
emulatorJarName + " not found in libs folder",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
ProcessBuilder pb = new ProcessBuilder(
"java", "-jar",
emulatorJar.getAbsolutePath(),
jarFile.getAbsolutePath()
);
pb.start(); // Launches external process, non-blocking
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Failed to launch " + emulatorName + ": " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
Assistant
Your EmulatorLauncher class looks straightforward and generally fine, but here are a few tips and small recommended improvements to make it more robust and cross-platform safe:
1. Use Canonical Paths for emulator and game JARs
This avoids possible issues with relative paths or symbolic links:
java
File emulatorJar = new File("libs", emulatorJarName);
try {
emulatorJar = emulatorJar.getCanonicalFile();
} catch (IOException e) {
// Optional: log or show a message
}
Similarly, you can do the same for jarFile to pass an absolute, canonical path.
2. Check that emulator and game JARs are readable
Before launching, check that the files exist and can be read to avoid a cryptic Java error when launching.
java
if (!emulatorJar.exists() || !emulatorJar.canRead()) {
JOptionPane.showMessageDialog(null,
emulatorJarName + " not found or not readable in libs folder",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (!jarFile.exists() || !jarFile.canRead()) {
JOptionPane.showMessageDialog(null,
"Game file not found or not readable: " + jarFile.getName(),
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
3. Use environment-independent "java" executable
Some platforms might require "java.exe" or custom java path. You could detect java.home JVM property if you want to be sure:
But often just "java" works on Windows/Linux/macOS assuming Java is in PATH.
4. Provide feedback about process start failure
Right now if pb.start() fails, you show a dialog, but errors launching the process later won't be caught.
If you want, you could read the process output or error stream asynchronously to capture errors (advanced).
public class ModsPanel extends JPanel {
private final DefaultListModel remoteModsModel = new DefaultListModel<>();
private final JList modsList;
code
Assistant
Your ModsPanel implementation looks quite solid! It uses Swing fairly idiomatically, handles async calls to fetch mod lists and download files off the Event Dispatch Thread (EDT), and updates the UI appropriately on the EDT. Your filtering and empty state logic also seems well though-out.
A few suggestions and tips to improve robustness, UX, and cross-platform behavior:
1. Thread pool executor reuse
You currently create a new single-thread executor every time you fetch or download mods. This is inefficient and can lead to resource leaks if not properly shutdown.
Suggestion: Declare a private final cached/single-thread executor for your panel, e.g.:
java
private final ExecutorService executor = Executors.newSingleThreadExecutor();
Use this executor to submit all background tasks and shut it down when your panel is disposed.
If you don’t have a lifecycle hook for the panel, it’s usually fine in a simple app, but it’s cleaner to reuse the executor.
2. Disable UI controls during background operations
You disable the "Fetch MODs" button while fetching, but the download button remains enabled until the user explicitly selects something.
Consider also disabling:
sourceSelector
Search field
during fetch and download to avoid confusing inconsistent UI states.
3. Check download directory validity before downloading
Technically, you set the directory at construction, but the user can change it.
Before downloading mods, you should do a check:
java
if (!downloadDir.exists() || !downloadDir.isDirectory() || !downloadDir.canWrite()) {
SwingUtilities.invokeLater(() -> setStatus("Download directory is invalid or not writable."));
return;
}
This feedback prevents file IO exceptions and mysterious failures.
4. Progress feedback for downloads
Your current UI updates status once after all downloads finish, but no progress shown during downloads.
You might:
Update status after each mod downloaded (SwingUtilities.invokeLater() inside the loop)
Or use a progress bar or dialog if you want better UX.
public class ModsPanel extends JPanel {
private final DefaultListModel remoteModsModel = new DefaultListModel<>();
private final JList modsList;
code
Assistant
Here's your updated ModsPanel with the requested enhancements incorporated:
Single shared executor for background tasks (fetching and downloading).
UI controls disabled/enabled appropriately during background work.
Download directory existence and writability checked before downloads.
Partial progress status updated per file downloaded.
Download meter showing progress bar while downloading mods.
Full updated ModsPanel with progress meter and fixes applied:
java
User
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':compileJava'.
Compilation failed; see the compiler output below.
/home/manish/IdeaProjects/HelloWorldGUI/src/main/java/org/nsomatrix/ModsPanel.java:348: error: local variables referenced from a lambda expression must be final or effectively final
setStatus("Downloaded " + successCount + " mod(s)."
^
1 error
Try:
Check your code and dependencies to fix the compilation error(s)
Run with --scan to get full insights.
BUILD FAILED in 1s
1 actionable task: 1 executed
manish@manish-vostro153568:~/IdeaProjects/HelloWorldGUI$
Assistant
The error:
code
local variables referenced from a lambda expression must be final or effectively final
refers to this line inside a lambda where you use local variable successCount, which is modified inside the enclosing method, so not effectively final.
How to fix: copy local variables that need to be captured inside lambdas into final or effectively final variables.
In your downloadSelectedMods(), to fix this error, you need to declare local final copies of successCount and failedMods when used inside the lambda.
Here, successCount and failedMods are modified in the method and referenced inside the lambda.
Fix 1: declare final copies before the lambda call:
java
final int finalSuccessCount = successCount;
final List<String> finalFailedMods = new ArrayList<>(failedMods);
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
setStatus("Downloaded " + finalSuccessCount + " mod(s)."
+ (finalFailedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", finalFailedMods))));
setUIEnabled(true);
});
Fix 2: Alternatively, create a static helper method to update UI passing these values explicitly (more refactor, but cleaner). Method 1 is simpler.
Below is the fixed relevant portion of your method:
java
User
give updated
Assistant
Certainly! Here's the updated downloadSelectedMods() method with the fix applied (final copies made before the lambda) and the relevant surrounding parts for clarity:
It's good to handle exceptions carefully, which you do.
You might want to use UTF-8 explicitly by using new OutputStreamWriter(new FileOutputStream(STORAGE_FILE), StandardCharsets.UTF_8) for portability and consistency (though default platform encoding is often fine).
Timestamp Format:
You use SimpleDateFormat to render the last played time in the list, which is clear and readable.
UI Styling:
Buttons have custom background colors and opaque settings to display nicely across look & feel themes.
Potential Improvements:
Sorting: Consider sorting the list by last played timestamp or alphabetically to improve UX.
Clear Message with Timeout: Currently, messages stay until next message is shown. You may want to clear messages after a delay.
Confirm Remove: Add a confirmation dialog before removing a game.
Executable Validation: Adding a check to validate the JAR file (maybe checking it contains a manifest) could prevent adding invalid files.
Better Error Handling: Communicate errors back to the user in the message label or dialogs.
You may want to verify or complement these points:
What does EmulatorLauncher.launch(emulator, file) return or throw? Are you handling launch failures well enough?
Confirm the UI#getSelectedEmulator() provides the correct emulator identifier.
If this UI can be resized, verify the appearance of the custom rendering and empty state looks good in various sizes.
If you want me to review or improve any specific part of this panel, or add features like sorting/games search/reordering, please let me know!
3. File Equality: Use Canonical Paths to Avoid Minor Differences
Currently, in containsFile(File file), you do:
java
gamesListModel.get(i).getFile().equals(file)
But File.equals() might fail if paths differ slightly (e.g., symbolic links, relative vs absolute, case differences on case-insensitive file systems).
Hotfix: Compare canonical paths that are normalized absolute paths.
Also update GameEntry.equals() and hashCode() similarly — store canonical path once in constructor if needed.
4. Drag and Drop: Accept Symlinks and Check File Accessibility
On Linux/macOS, dropped files can be symlinks or shortcuts.
Before launching, verify file.canRead() and file.isFile() to avoid broken symlinks or inaccessible files that could cause errors.
In your drag-and-drop and add logic, check:
java
if (isJarFile(f) && f.canRead()) {
...
}
5. UI: Use Platform Default Fonts and Sizes
You hardcode "SansSerif" font family and sizes, which may vary in look on different platforms.
Hotfix:
Use platform default fonts where possible, e.g.:
java
Font defaultFont = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 18f);
gamesLabel.setFont(defaultFont);
This makes your UI integrate better with native apps on each OS.
6. File Chooser: Set Current Directory
When showing the file chooser, it opens in the last used directory or user's home directory by default.
Hotfix: Remember and restore the last used directory for user convenience:
java
private File lastDir = null;
private void addGame() {
JFileChooser chooser = new JFileChooser();
if (lastDir != null) {
chooser.setCurrentDirectory(lastDir);
}
...
if (result == JFileChooser.APPROVE_OPTION) {
File jar = chooser.getSelectedFile();
lastDir = jar.getParentFile();
...
}
}
7. Button Backgrounds and Look & Feel:
You've set buttons with setOpaque(true) and custom background colors. Good, but on macOS with the Aqua look, buttons may not respect these well.
Hotfix: To keep platform appearance friendly, optionally set setContentAreaFilled(false) on macOS or add a check:
java
if (!UIManager.getLookAndFeel().getName().toLowerCase().contains("aqua")) {
launchBtn.setOpaque(true);
launchBtn.setBackground(new Color(0, 128, 0));
...
}
Or consider using standard buttons for macOS users to keep native feel.
8. Lock File for Storage (Optional, Advanced)
If your app can be run multiple times or from multiple JVM instances, writes may collide.
Hotfix: Use file locks (via FileChannel.lock()) or synchronize writes.
Summary of Critical Hotfixes for Cross-Platform Robustness
Fix
Why?
How?
Use canonical paths when comparing files
Relative/symlinked paths differ
File.getCanonicalPath()
Use UTF-8 explicitly for storage I/O
Encoding mismatch on some platforms
use InputStreamReader/OutputStreamWriter with charset
Check file readability/accessibility
Prevent errors from dropped broken links
Check file.canRead()
Use platform default fonts
Better native UI integration
UIManager.getFont(...)
Persist last used directory for file chooser
Better UX across sessions
Save last directory path
Handle button styles per platform
Fix button appearance (especially on macOS)
Conditional opaque + BG color
If you implement these quick fixes, your app will be much more robust and reliable across Windows/macOS/Linux and users with diverse locales.
If you want, I can help provide diff snippets or improved implementations for any of these points!
private final UI appUI;
private final DefaultListModel<GameEntry> gamesListModel = new DefaultListModel<>();
private final JList<GameEntry> gamesList;
private final JButton launchBtn;
private final JButton removeBtn;
private final JLabel messageLabel;
private final JPanel emptyStatePanel;
public EmuRunPanel(UI ui) {
this.appUI = ui;
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel gamesLabel = new JLabel("Available Games");
gamesLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
add(gamesLabel, BorderLayout.NORTH);
gamesList = new JList<>(gamesListModel);
gamesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
gamesList.setCellRenderer(new GameEntryCellRenderer());
JScrollPane scrollPane = new JScrollPane(gamesList);
emptyStatePanel = createEmptyStatePanel();
emptyStatePanel.setVisible(gamesListModel.isEmpty());
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
gamesListModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override public void intervalAdded(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void intervalRemoved(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void contentsChanged(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
});
updateEmptyStateVisibility();
enableFileDragAndDrop(this);
enableFileDragAndDrop(gamesList);
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
launchBtn = new JButton("Launch");
launchBtn.setEnabled(false);
launchBtn.addActionListener(e -> launchSelectedGame());
launchBtn.setBackground(new Color(0, 128, 0));
launchBtn.setForeground(Color.WHITE);
launchBtn.setOpaque(true);
launchBtn.setBorderPainted(false);
JButton addBtn = new JButton("Add Game");
addBtn.addActionListener(e -> addGame());
removeBtn = new JButton("Remove");
removeBtn.setEnabled(false);
removeBtn.addActionListener(e -> removeSelectedGame());
removeBtn.setBackground(new Color(200, 0, 0));
removeBtn.setForeground(Color.WHITE);
removeBtn.setOpaque(true);
removeBtn.setBorderPainted(false);
buttonsPanel.add(addBtn);
buttonsPanel.add(removeBtn);
buttonsPanel.add(launchBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
messageLabel = new JLabel(" ");
messageLabel.setForeground(Color.GRAY);
bottomPanel.add(messageLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
gamesList.addListSelectionListener(e -> updateButtons());
gamesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
launchSelectedGame();
}
}
});
loadGamesFromStorage();
}
private JPanel createEmptyStatePanel() {
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel iconLabel = new JLabel(new DragDropIcon(64, 64));
iconLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel textLabel = new JLabel("Drag and Drop or Select JAR to Launch");
textLabel.setFont(new Font("SansSerif", Font.BOLD, 22));
textLabel.setForeground(Color.GRAY);
textLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
textLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
panel.add(iconLabel);
panel.add(textLabel);
return panel;
}
private void updateEmptyStateVisibility() {
emptyStatePanel.setVisible(gamesListModel.isEmpty());
}
private void enableFileDragAndDrop(Component comp) {
new DropTarget(comp, new DropTargetListener() {
@Override public void dragEnter(DropTargetDragEvent dtde) {
if (canAcceptDrop(dtde)) dtde.acceptDrag(DnDConstants.ACTION_COPY);
else dtde.rejectDrag();
}
@Override public void dragOver(DropTargetDragEvent dtde) {}
@Override public void dropActionChanged(DropTargetDragEvent dtde) {}
@Override public void dragExit(DropTargetEvent dte) {}
@Override
public void drop(DropTargetDropEvent dtde) {
try {
if (canAcceptDrop(dtde)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
@SuppressWarnings("unchecked")
List<File> droppedFiles = (List<File>) dtde.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
int launchedCount = 0;
for (File f : droppedFiles) {
if (isJarFile(f)) {
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, f);
if (!containsFile(f)) {
gamesListModel.addElement(new GameEntry(f, 0));
saveGamesToStorage();
}
launchedCount++;
}
}
if (launchedCount > 0)
setMessage("Launched " + launchedCount + " game(s) by drag and drop.");
else
setMessage("No valid JAR files found in drop.");
dtde.dropComplete(true);
} else {
dtde.rejectDrop();
}
} catch (Exception ex) {
ex.printStackTrace();
setMessage("Error processing dropped files.");
dtde.dropComplete(false);
}
}
private boolean canAcceptDrop(DropTargetDragEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
private boolean canAcceptDrop(DropTargetDropEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
});
}
private boolean isJarFile(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
private void addGame() {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("JAR Files", "jar"));
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File jar = chooser.getSelectedFile();
if (!containsFile(jar)) {
gamesListModel.addElement(new GameEntry(jar, 0));
saveGamesToStorage();
setMessage("Added: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
} else {
setMessage("Game already in list: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
}
}
}
private void removeSelectedGame() {
int idx = gamesList.getSelectedIndex();
if (idx >= 0) {
GameEntry removed = gamesListModel.getElementAt(idx);
gamesListModel.remove(idx);
saveGamesToStorage();
setMessage("Removed: " + removed.getFile().getName());
}
}
private void launchSelectedGame() {
GameEntry selectedEntry = gamesList.getSelectedValue();
if (selectedEntry != null) {
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, selectedEntry.getFile());
setMessage("Launching: " + selectedEntry.getFile().getName());
// Update last played timestamp
selectedEntry.setLastPlayedTimestamp(System.currentTimeMillis());
saveGamesToStorage();
gamesList.repaint();
} else {
setMessage("No game selected to launch.");
}
}
private void updateButtons() {
boolean selected = gamesList.getSelectedIndex() >= 0;
launchBtn.setEnabled(selected);
removeBtn.setEnabled(selected);
}
private void setMessage(String message) {
messageLabel.setText(message);
}
private boolean containsFile(File file) {
for (int i = 0; i < gamesListModel.size(); i++) {
if (gamesListModel.get(i).getFile().equals(file)) {
return true;
}
}
return false;
}
private void saveGamesToStorage() {
try (PrintWriter pw = new PrintWriter(new FileWriter(STORAGE_FILE))) {
for (int i = 0; i < gamesListModel.size(); i++) {
GameEntry entry = gamesListModel.get(i);
pw.println(entry.getFile().getAbsolutePath() + "|" + entry.getLastPlayedTimestamp());
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to save games list.");
}
}
private void loadGamesFromStorage() {
if (!STORAGE_FILE.exists()) return;
try (BufferedReader br = new BufferedReader(new FileReader(STORAGE_FILE))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\\|");
File file = new File(parts[0]);
long ts = 0L;
if (parts.length > 1) {
try {
ts = Long.parseLong(parts[1]);
} catch (NumberFormatException ignored) {}
}
if (file.exists() && isJarFile(file)) {
GameEntry entry = new GameEntry(file, ts);
if (!containsFile(file)) {
gamesListModel.addElement(entry);
}
}
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to load saved games.");
}
}
private static class GameEntry {
private final File file;
private long lastPlayedTimestamp;
public GameEntry(File file, long lastPlayedTimestamp) {
this.file = file;
this.lastPlayedTimestamp = lastPlayedTimestamp;
}
public File getFile() {
return file;
}
public long getLastPlayedTimestamp() {
return lastPlayedTimestamp;
}
public void setLastPlayedTimestamp(long timestamp) {
this.lastPlayedTimestamp = timestamp;
}
@Override
public String toString() {
return file.getName();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
GameEntry that = (GameEntry) other;
return file.equals(that.file);
}
@Override
public int hashCode() {
return file.hashCode();
}
}
private class GameEntryCellRenderer extends DefaultListCellRenderer {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof GameEntry) {
GameEntry ge = (GameEntry) value;
File file = ge.getFile();
long sizeKb = (file.length() + 1023) / 1024; // rounded KB
String lastPlayedStr = ge.getLastPlayedTimestamp() > 0
? dateFormat.format(new Date(ge.getLastPlayedTimestamp()))
: "Never";
label.setText(String.format("<html>%s<br/><small>Size: %d KB | Last Played: %s</small></html>",
file.getName(), sizeKb, lastPlayedStr));
}
return label;
}
}
private static class DragDropIcon implements Icon {
private final int width;
private final int height;
public DragDropIcon(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.LIGHT_GRAY);
int centerX = x + width / 2;
int centerY = y + height / 2;
g2d.setStroke(new BasicStroke(6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
g2d.drawLine(centerX, y + 10, centerX, y + height - 20);
Polygon arrowHead = new Polygon();
arrowHead.addPoint(centerX - 15, y + height - 45);
arrowHead.addPoint(centerX + 15, y + height - 45);
arrowHead.addPoint(centerX, y + height - 10);
g2d.fill(arrowHead);
} finally {
g2d.dispose();
}
}
@Override
public int getIconWidth() {
return width;
}
@Override
public int getIconHeight() {
return height;
}
}
}
package org.nsomatrix.ui;
import org.nsomatrix.EmulatorLauncher;
import org.nsomatrix.UI;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class EmuRunPanel extends JPanel {
private static final File STORAGE_FILE = new File(System.getProperty("user.home"), ".matrix_launcher_games.txt");
private final UI appUI;
private final DefaultListModel<GameEntry> gamesListModel = new DefaultListModel<>();
private final JList<GameEntry> gamesList;
private final JButton launchBtn;
private final JButton removeBtn;
private final JLabel messageLabel;
private final JPanel emptyStatePanel;
// Remember last directory used for JFileChooser
private File lastUsedDir = null;
public EmuRunPanel(UI ui) {
this.appUI = ui;
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(20, 20, 20, 20));
// Use platform default font for labels and sizes
Font labelFont = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 18f);
JLabel gamesLabel = new JLabel("Available Games");
gamesLabel.setFont(labelFont);
add(gamesLabel, BorderLayout.NORTH);
gamesList = new JList<>(gamesListModel);
gamesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
gamesList.setCellRenderer(new GameEntryCellRenderer());
JScrollPane scrollPane = new JScrollPane(gamesList);
emptyStatePanel = createEmptyStatePanel();
emptyStatePanel.setVisible(gamesListModel.isEmpty());
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
gamesListModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override public void intervalAdded(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void intervalRemoved(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
@Override public void contentsChanged(javax.swing.event.ListDataEvent e) { updateEmptyStateVisibility(); }
});
updateEmptyStateVisibility();
enableFileDragAndDrop(this);
enableFileDragAndDrop(gamesList);
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
launchBtn = new JButton("Launch");
launchBtn.setEnabled(false);
launchBtn.addActionListener(e -> launchSelectedGame());
// Conditional button styling to avoid macOS Aqua painting issues
if (!UIManager.getLookAndFeel().getName().toLowerCase().contains("aqua")) {
launchBtn.setBackground(new Color(0, 128, 0));
launchBtn.setForeground(Color.WHITE);
launchBtn.setOpaque(true);
launchBtn.setBorderPainted(false);
}
JButton addBtn = new JButton("Add Game");
addBtn.addActionListener(e -> addGame());
removeBtn = new JButton("Remove");
removeBtn.setEnabled(false);
removeBtn.addActionListener(e -> removeSelectedGame());
if (!UIManager.getLookAndFeel().getName().toLowerCase().contains("aqua")) {
removeBtn.setBackground(new Color(200, 0, 0));
removeBtn.setForeground(Color.WHITE);
removeBtn.setOpaque(true);
removeBtn.setBorderPainted(false);
}
buttonsPanel.add(addBtn);
buttonsPanel.add(removeBtn);
buttonsPanel.add(launchBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
messageLabel = new JLabel(" ");
messageLabel.setForeground(Color.GRAY);
bottomPanel.add(messageLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
gamesList.addListSelectionListener(e -> updateButtons());
gamesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
launchSelectedGame();
}
}
});
loadGamesFromStorage();
}
private JPanel createEmptyStatePanel() {
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel iconLabel = new JLabel(new DragDropIcon(64, 64));
iconLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
Font font = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 22f);
JLabel textLabel = new JLabel("Drag and Drop or Select JAR to Launch");
textLabel.setFont(font);
textLabel.setForeground(Color.GRAY);
textLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
textLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
panel.add(iconLabel);
panel.add(textLabel);
return panel;
}
private void updateEmptyStateVisibility() {
emptyStatePanel.setVisible(gamesListModel.isEmpty());
}
private void enableFileDragAndDrop(Component comp) {
new DropTarget(comp, new DropTargetListener() {
@Override public void dragEnter(DropTargetDragEvent dtde) {
if (canAcceptDrop(dtde)) dtde.acceptDrag(DnDConstants.ACTION_COPY);
else dtde.rejectDrag();
}
@Override public void dragOver(DropTargetDragEvent dtde) {}
@Override public void dropActionChanged(DropTargetDragEvent dtde) {}
@Override public void dragExit(DropTargetEvent dte) {}
@Override
public void drop(DropTargetDropEvent dtde) {
try {
if (canAcceptDrop(dtde)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
@SuppressWarnings("unchecked")
List<File> droppedFiles = (List<File>) dtde.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
int launchedCount = 0;
for (File f : droppedFiles) {
if (isJarFile(f) && f.canRead()) { // <-- check readability
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, f);
if (!containsFile(f)) {
gamesListModel.addElement(new GameEntry(f, 0));
saveGamesToStorage();
}
launchedCount++;
}
}
if (launchedCount > 0)
setMessage("Launched " + launchedCount + " game(s) by drag and drop.");
else
setMessage("No valid readable JAR files found in drop.");
dtde.dropComplete(true);
} else {
dtde.rejectDrop();
}
} catch (Exception ex) {
ex.printStackTrace();
setMessage("Error processing dropped files.");
dtde.dropComplete(false);
}
}
private boolean canAcceptDrop(DropTargetDragEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
private boolean canAcceptDrop(DropTargetDropEvent dtde) {
return dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
});
}
private boolean isJarFile(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
private void addGame() {
JFileChooser chooser = new JFileChooser();
if (lastUsedDir != null && lastUsedDir.exists()) {
chooser.setCurrentDirectory(lastUsedDir);
}
chooser.setFileFilter(new FileNameExtensionFilter("JAR Files", "jar"));
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File jar = chooser.getSelectedFile();
lastUsedDir = jar.getParentFile();
if (jar.canRead() && !containsFile(jar)) {
gamesListModel.addElement(new GameEntry(jar, 0));
saveGamesToStorage();
setMessage("Added: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
} else if (containsFile(jar)) {
setMessage("Game already in list: " + jar.getName());
gamesList.setSelectedValue(new GameEntry(jar, 0), true);
} else {
setMessage("Cannot read selected file: " + jar.getName());
}
}
}
private void removeSelectedGame() {
int idx = gamesList.getSelectedIndex();
if (idx >= 0) {
GameEntry removed = gamesListModel.getElementAt(idx);
gamesListModel.remove(idx);
saveGamesToStorage();
setMessage("Removed: " + removed.getFile().getName());
}
}
private void launchSelectedGame() {
GameEntry selectedEntry = gamesList.getSelectedValue();
if (selectedEntry != null) {
String emulator = appUI.getSelectedEmulator();
EmulatorLauncher.launch(emulator, selectedEntry.getFile());
setMessage("Launching: " + selectedEntry.getFile().getName());
// Update last played timestamp
selectedEntry.setLastPlayedTimestamp(System.currentTimeMillis());
saveGamesToStorage();
gamesList.repaint();
} else {
setMessage("No game selected to launch.");
}
}
private void updateButtons() {
boolean selected = gamesList.getSelectedIndex() >= 0;
launchBtn.setEnabled(selected);
removeBtn.setEnabled(selected);
}
private void setMessage(String message) {
messageLabel.setText(message);
}
private boolean containsFile(File file) {
try {
String canonicalPath = file.getCanonicalPath();
for (int i = 0; i < gamesListModel.size(); i++) {
if (gamesListModel.get(i).getFile().getCanonicalPath().equals(canonicalPath)) {
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private void saveGamesToStorage() {
// Use UTF-8 explicitly
try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(STORAGE_FILE), StandardCharsets.UTF_8))) {
for (int i = 0; i < gamesListModel.size(); i++) {
GameEntry entry = gamesListModel.get(i);
// Use canonical path for storage
try {
String path = entry.getFile().getCanonicalPath();
pw.println(path + "|" + entry.getLastPlayedTimestamp());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to save games list.");
}
}
private void loadGamesFromStorage() {
if (!STORAGE_FILE.exists()) return;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(STORAGE_FILE), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("\\|");
File file = new File(parts[0]);
long ts = 0L;
if (parts.length > 1) {
try {
ts = Long.parseLong(parts[1]);
} catch (NumberFormatException ignored) {}
}
if (file.exists() && isJarFile(file) && file.canRead()) {
GameEntry entry = new GameEntry(file, ts);
if (!containsFile(file)) {
gamesListModel.addElement(entry);
}
}
}
} catch (IOException e) {
e.printStackTrace();
setMessage("Failed to load saved games.");
}
}
private static class GameEntry {
private final File file;
private long lastPlayedTimestamp;
public GameEntry(File file, long lastPlayedTimestamp) {
this.file = file;
this.lastPlayedTimestamp = lastPlayedTimestamp;
}
public File getFile() {
return file;
}
public long getLastPlayedTimestamp() {
return lastPlayedTimestamp;
}
public void setLastPlayedTimestamp(long timestamp) {
this.lastPlayedTimestamp = timestamp;
}
@Override
public String toString() {
return file.getName();
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
GameEntry that = (GameEntry) other;
try {
return this.file.getCanonicalPath().equals(that.file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
return this.file.equals(that.file);
}
}
@Override
public int hashCode() {
try {
return file.getCanonicalPath().hashCode();
} catch (IOException e) {
e.printStackTrace();
return file.hashCode();
}
}
}
private class GameEntryCellRenderer extends DefaultListCellRenderer {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof GameEntry) {
GameEntry ge = (GameEntry) value;
File file = ge.getFile();
long sizeKb = (file.length() + 1023) / 1024; // rounded KB
String lastPlayedStr = ge.getLastPlayedTimestamp() > 0
? dateFormat.format(new Date(ge.getLastPlayedTimestamp()))
: "Never";
label.setText(String.format("<html>%s<br/><small>Size: %d KB | Last Played: %s</small></html>",
file.getName(), sizeKb, lastPlayedStr));
}
return label;
}
}
private static class DragDropIcon implements Icon {
private final int width;
private final int height;
public DragDropIcon(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.LIGHT_GRAY);
int centerX = x + width / 2;
int centerY = y + height / 2;
g2d.setStroke(new BasicStroke(6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
g2d.drawLine(centerX, y + 10, centerX, y + height - 20);
Polygon arrowHead = new Polygon();
arrowHead.addPoint(centerX - 15, y + height - 45);
arrowHead.addPoint(centerX + 15, y + height - 45);
arrowHead.addPoint(centerX, y + height - 10);
g2d.fill(arrowHead);
} finally {
g2d.dispose();
}
}
@Override
public int getIconWidth() {
return width;
}
@Override
public int getIconHeight() {
return height;
}
}
}
What Changed
File comparisons now use file.getCanonicalPath() inside containsFile() and GameEntry.equals/hashCode() to reliably identify the same path even if symlinks or variations in path notation occur.
File I/O (save/load) uses UTF-8 explicitly to avoid encoding issues.
File readability (canRead()) checks added before adding or launching files.
FileChooser remembers last used directory for improved UX.
UI fonts for labels come from platform defaults instead of hardcoded fonts.
Button colors are conditionally applied: on macOS with Aqua L&F, they keep native look by skipping background and opacity changes.
Minor messages improved for clarity.
These improvements will increase the reliability of your launcher across OS boundaries and user environments.
If you want me to help with additional features or testing tips - just ask!
5. (Optional) Run the process in a separate thread
Since pb.start() is non-blocking, it's okay, but you might want to capture its exit status or errors in a separate thread if needed.
Full revised version incorporating above:
java
package org.nsomatrix;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
public class EmulatorLauncher {
public static void launch(String emulatorName, File jarFile) {
String emulatorJarName;
switch (emulatorName.toLowerCase()) {
case "angelchip":
emulatorJarName = "angelchip.jar";
break;
case "microemulator":
default:
emulatorJarName = "microemulator.jar";
break;
}
File emulatorJar = new File("libs", emulatorJarName);
try {
emulatorJar = emulatorJar.getCanonicalFile();
jarFile = jarFile.getCanonicalFile();
} catch (IOException e) {
// Could show message or log
}
if (!emulatorJar.exists() || !emulatorJar.canRead()) {
JOptionPane.showMessageDialog(null,
emulatorJarName + " not found or unreadable in libs folder",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (!jarFile.exists() || !jarFile.canRead()) {
JOptionPane.showMessageDialog(null,
"Game file not found or unreadable: " + jarFile.getName(),
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Use absolute java path or simple "java" command (assuming Java in PATH)
String javaExec = "java";
try {
ProcessBuilder pb = new ProcessBuilder(
javaExec, "-jar",
emulatorJar.getAbsolutePath(),
jarFile.getAbsolutePath()
);
pb.start();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Failed to launch " + emulatorName + ": " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
Summary
This version:
Protects against relative/symlink path quirks,
Checks file existence and readability before launching,
Is mostly cross-platform safe,
Shows clear error dialogs on failure.
If you plan to improve further with logging or asynchronously capturing stdout/stderr from the launched process, I can help with that too!
private final JButton fetchModsBtn;
private final JButton downloadSelectedBtn;
private final JComboBox<String> sourceSelector;
private final JTextField downloadDirField;
private final JButton chooseDownloadDirBtn;
private final JLabel statusLabel;
private final JTextField searchField;
private final JPanel emptyStatePanel;
private File downloadDir = new File(System.getProperty("user.home"), "Downloads/mods");
// Keep a master list of all mods fetched (unfiltered)
private final List<RemoteMod> allMods = new ArrayList<>();
// Sources and their data URLs
private final String GITHUB_API_URL = "https://api.github.com/repos/cloudkore/matrix/contents/data/MODs";
private final String INTERNET_ARCHIVE_METADATA_URL = "https://archive.org/metadata/nsomtxmods";
public ModsPanel() {
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel titleLabel = new JLabel("Mods");
titleLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(titleLabel, BorderLayout.NORTH);
// Search bar
searchField = new JTextField(30);
searchField.setToolTipText("Search mods...");
searchField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void removeUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void changedUpdate(DocumentEvent e) {
filterMods();
}
});
// Top panel with source selector and search
JPanel topPanel = new JPanel(new BorderLayout(5, 5));
JPanel sourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
sourcePanel.add(new JLabel("Source:"));
sourceSelector = new JComboBox<>(new String[]{"GitHub", "Internet Archive"});
sourcePanel.add(sourceSelector);
topPanel.add(sourcePanel, BorderLayout.WEST);
topPanel.add(searchField, BorderLayout.CENTER);
add(topPanel, BorderLayout.PAGE_START);
modsList = new JList<>(remoteModsModel);
modsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
if (value instanceof RemoteMod) {
label.setText(((RemoteMod) value).name);
}
return label;
}
});
JScrollPane scrollPane = new JScrollPane(modsList);
// Create empty placeholder panel with only the text, no icon
emptyStatePanel = new JPanel();
emptyStatePanel.setLayout(new BoxLayout(emptyStatePanel, BoxLayout.Y_AXIS));
emptyStatePanel.setOpaque(false);
emptyStatePanel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel placeholderLabel = new JLabel(" Select Source to fetch MODs");
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setFont(new Font("SansSerif", Font.BOLD, 22)); // big and bold
placeholderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
placeholderLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
emptyStatePanel.add(placeholderLabel);
// Panel to overlay emptyStatePanel on top of scrollPane
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
// Bottom panel with buttons and download dir
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
fetchModsBtn = new JButton("Fetch MODs");
fetchModsBtn.addActionListener(e -> fetchMods());
downloadSelectedBtn = new JButton("Download");
downloadSelectedBtn.setEnabled(false);
downloadSelectedBtn.addActionListener(e -> downloadSelectedMods());
buttonsPanel.add(fetchModsBtn);
buttonsPanel.add(downloadSelectedBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
JPanel downloadDirPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
downloadDirField = new JTextField(downloadDir.getAbsolutePath(), 30);
chooseDownloadDirBtn = new JButton("Choose Download Folder");
chooseDownloadDirBtn.addActionListener(e -> chooseDownloadDirectory());
downloadDirPanel.add(new JLabel("Download Folder:"));
downloadDirPanel.add(downloadDirField);
downloadDirPanel.add(chooseDownloadDirBtn);
bottomPanel.add(downloadDirPanel, BorderLayout.CENTER);
statusLabel = new JLabel(" ");
statusLabel.setForeground(Color.GRAY);
bottomPanel.add(statusLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
modsList.addListSelectionListener(e -> downloadSelectedBtn.setEnabled(!modsList.isSelectionEmpty()));
// Update placeholder visibility when model changes:
remoteModsModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override
public void intervalAdded(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void intervalRemoved(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void contentsChanged(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
});
updateEmptyStateVisibility();
if (!downloadDir.exists()) {
downloadDir.mkdirs();
}
}
private void updateEmptyStateVisibility() {
boolean noItemsToShow = remoteModsModel.isEmpty();
emptyStatePanel.setVisible(noItemsToShow);
}
private void filterMods() {
String filter = searchField.getText().trim().toLowerCase();
remoteModsModel.clear();
if (filter.isEmpty()) {
// Show all mods
allMods.forEach(remoteModsModel::addElement);
} else {
// Show filtered mods only
List<RemoteMod> filtered = allMods.stream()
.filter(mod -> mod.name.toLowerCase().contains(filter))
.collect(Collectors.toList());
filtered.forEach(remoteModsModel::addElement);
}
}
private void fetchMods() {
setStatus("Fetching mod list...");
allMods.clear();
remoteModsModel.clear();
String source = (String) sourceSelector.getSelectedItem();
String apiUrl = "Internet Archive".equals(source) ? INTERNET_ARCHIVE_METADATA_URL : GITHUB_API_URL;
fetchModsBtn.setEnabled(false);
Executors.newSingleThreadExecutor().submit(() -> {
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Accept", "application/vnd.github.v3+json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
SwingUtilities.invokeLater(() -> {
setStatus("Failed to fetch mods: HTTP " + response.statusCode());
fetchModsBtn.setEnabled(true);
});
return;
}
ObjectMapper mapper = new ObjectMapper();
List<RemoteMod> fetchedMods = new ArrayList<>();
if ("Internet Archive".equals(source)) {
JsonNode root = mapper.readTree(response.body());
JsonNode filesArray = root.get("files");
if (filesArray != null && filesArray.isArray()) {
for (JsonNode fileNode : filesArray) {
String name = fileNode.get("name").asText();
if (name.toLowerCase().endsWith(".jar")) {
String downloadUrl = "https://archive.org/download/nsomtxmods/" + name;
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
} else {
JsonNode root = mapper.readTree(response.body());
for (JsonNode node : root) {
String name = node.get("name").asText();
String downloadUrl = node.get("download_url").asText();
if (name.toLowerCase().endsWith(".jar")) {
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
SwingUtilities.invokeLater(() -> {
allMods.clear();
allMods.addAll(fetchedMods);
filterMods(); // show filtered results (empty filter shows all)
setStatus("Fetched " + fetchedMods.size() + " mods from " + source);
fetchModsBtn.setEnabled(true);
});
} catch (Exception e) {
e.printStackTrace();
SwingUtilities.invokeLater(() -> {
setStatus("Error fetching mods: " + e.getMessage());
fetchModsBtn.setEnabled(true);
});
}
});
}
private void downloadSelectedMods() {
List<RemoteMod> selectedMods = modsList.getSelectedValuesList();
setStatus("Downloading " + selectedMods.size() + " mod(s)...");
Executors.newSingleThreadExecutor().submit(() -> {
int successCount = 0;
for (RemoteMod mod : selectedMods) {
try {
File targetFile = new File(downloadDir, mod.name);
if (targetFile.exists()) {
// skip existing
continue;
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(mod.downloadUrl))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() == 200) {
try (InputStream in = response.body();
FileOutputStream fos = new FileOutputStream(targetFile)) {
in.transferTo(fos);
}
successCount++;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
final int downloaded = successCount;
SwingUtilities.invokeLater(() ->
setStatus("Downloaded " + downloaded + " mod(s)."));
});
}
private void chooseDownloadDirectory() {
JFileChooser chooser = new JFileChooser(downloadDir);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = chooser.showOpenDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
File dir = chooser.getSelectedFile();
if (dir.exists() && dir.isDirectory()) {
downloadDir = dir;
downloadDirField.setText(downloadDir.getAbsolutePath());
setStatus("Download folder set to: " + downloadDir.getAbsolutePath());
} else {
setStatus("Invalid directory selected.");
}
}
}
private void setStatus(String message) {
statusLabel.setText(message);
}
private static class RemoteMod {
public final String name;
public final String downloadUrl;
public RemoteMod(String name, String downloadUrl) {
this.name = name;
this.downloadUrl = downloadUrl;
}
@Override
public String toString() {
return name;
}
}
}
5. Handle partial downloads
You currently skip files if they already exist. That's good, but you might want to offer a “redownload" option (later feature).
Also, consider writing into a temporary file first, then rename to final filename when complete — prevents partial corrupt files.
6. Improve error feedback
Currently, failures during download are just printed to console.
Consider collecting failed mod names, and after download finishes, display which failed (or how many failed).
Your code is a very good Swing implementation for remote mod management. The above suggestions mostly improve robustness, UX polish, and resource management, particularly thread usage and user feedback during async operations.
If you want, I can help you incorporate these changes fully or review the next steps!
private final JButton fetchModsBtn;
private final JButton downloadSelectedBtn;
private final JComboBox<String> sourceSelector;
private final JTextField downloadDirField;
private final JButton chooseDownloadDirBtn;
private final JLabel statusLabel;
private final JTextField searchField;
private final JPanel emptyStatePanel;
private File downloadDir = new File(System.getProperty("user.home"), "Downloads/mods");
// Keep a master list of all mods fetched (unfiltered)
private final List<RemoteMod> allMods = new ArrayList<>();
// Sources and their data URLs
private final String GITHUB_API_URL = "https://api.github.com/repos/cloudkore/matrix/contents/data/MODs";
private final String INTERNET_ARCHIVE_METADATA_URL = "https://archive.org/metadata/nsomtxmods";
public ModsPanel() {
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel titleLabel = new JLabel("Mods");
titleLabel.setFont(new Font("SansSerif", Font.BOLD, 18));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(titleLabel, BorderLayout.NORTH);
// Search bar
searchField = new JTextField(30);
searchField.setToolTipText("Search mods...");
searchField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void removeUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void changedUpdate(DocumentEvent e) {
filterMods();
}
});
// Top panel with source selector and search
JPanel topPanel = new JPanel(new BorderLayout(5, 5));
JPanel sourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
sourcePanel.add(new JLabel("Source:"));
sourceSelector = new JComboBox<>(new String[]{"GitHub", "Internet Archive"});
sourcePanel.add(sourceSelector);
topPanel.add(sourcePanel, BorderLayout.WEST);
topPanel.add(searchField, BorderLayout.CENTER);
add(topPanel, BorderLayout.PAGE_START);
modsList = new JList<>(remoteModsModel);
modsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
if (value instanceof RemoteMod) {
label.setText(((RemoteMod) value).name);
}
return label;
}
});
JScrollPane scrollPane = new JScrollPane(modsList);
// Create empty placeholder panel with only the text, no icon
emptyStatePanel = new JPanel();
emptyStatePanel.setLayout(new BoxLayout(emptyStatePanel, BoxLayout.Y_AXIS));
emptyStatePanel.setOpaque(false);
emptyStatePanel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel placeholderLabel = new JLabel(" Select Source to fetch MODs");
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setFont(new Font("SansSerif", Font.BOLD, 22)); // big and bold
placeholderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
placeholderLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
emptyStatePanel.add(placeholderLabel);
// Panel to overlay emptyStatePanel on top of scrollPane
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
// Bottom panel with buttons and download dir
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
fetchModsBtn = new JButton("Fetch MODs");
fetchModsBtn.addActionListener(e -> fetchMods());
downloadSelectedBtn = new JButton("Download");
downloadSelectedBtn.setEnabled(false);
downloadSelectedBtn.addActionListener(e -> downloadSelectedMods());
buttonsPanel.add(fetchModsBtn);
buttonsPanel.add(downloadSelectedBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
JPanel downloadDirPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
downloadDirField = new JTextField(downloadDir.getAbsolutePath(), 30);
chooseDownloadDirBtn = new JButton("Choose Download Folder");
chooseDownloadDirBtn.addActionListener(e -> chooseDownloadDirectory());
downloadDirPanel.add(new JLabel("Download Folder:"));
downloadDirPanel.add(downloadDirField);
downloadDirPanel.add(chooseDownloadDirBtn);
bottomPanel.add(downloadDirPanel, BorderLayout.CENTER);
statusLabel = new JLabel(" ");
statusLabel.setForeground(Color.GRAY);
bottomPanel.add(statusLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
modsList.addListSelectionListener(e -> downloadSelectedBtn.setEnabled(!modsList.isSelectionEmpty()));
// Update placeholder visibility when model changes:
remoteModsModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override
public void intervalAdded(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void intervalRemoved(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void contentsChanged(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
});
updateEmptyStateVisibility();
if (!downloadDir.exists()) {
downloadDir.mkdirs();
}
}
private void updateEmptyStateVisibility() {
boolean noItemsToShow = remoteModsModel.isEmpty();
emptyStatePanel.setVisible(noItemsToShow);
}
private void filterMods() {
String filter = searchField.getText().trim().toLowerCase();
remoteModsModel.clear();
if (filter.isEmpty()) {
// Show all mods
allMods.forEach(remoteModsModel::addElement);
} else {
// Show filtered mods only
List<RemoteMod> filtered = allMods.stream()
.filter(mod -> mod.name.toLowerCase().contains(filter))
.collect(Collectors.toList());
filtered.forEach(remoteModsModel::addElement);
}
}
private void fetchMods() {
setStatus("Fetching mod list...");
allMods.clear();
remoteModsModel.clear();
String source = (String) sourceSelector.getSelectedItem();
String apiUrl = "Internet Archive".equals(source) ? INTERNET_ARCHIVE_METADATA_URL : GITHUB_API_URL;
fetchModsBtn.setEnabled(false);
Executors.newSingleThreadExecutor().submit(() -> {
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Accept", "application/vnd.github.v3+json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
SwingUtilities.invokeLater(() -> {
setStatus("Failed to fetch mods: HTTP " + response.statusCode());
fetchModsBtn.setEnabled(true);
});
return;
}
ObjectMapper mapper = new ObjectMapper();
List<RemoteMod> fetchedMods = new ArrayList<>();
if ("Internet Archive".equals(source)) {
JsonNode root = mapper.readTree(response.body());
JsonNode filesArray = root.get("files");
if (filesArray != null && filesArray.isArray()) {
for (JsonNode fileNode : filesArray) {
String name = fileNode.get("name").asText();
if (name.toLowerCase().endsWith(".jar")) {
String downloadUrl = "https://archive.org/download/nsomtxmods/" + name;
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
} else {
JsonNode root = mapper.readTree(response.body());
for (JsonNode node : root) {
String name = node.get("name").asText();
String downloadUrl = node.get("download_url").asText();
if (name.toLowerCase().endsWith(".jar")) {
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
SwingUtilities.invokeLater(() -> {
allMods.clear();
allMods.addAll(fetchedMods);
filterMods(); // show filtered results (empty filter shows all)
setStatus("Fetched " + fetchedMods.size() + " mods from " + source);
fetchModsBtn.setEnabled(true);
});
} catch (Exception e) {
e.printStackTrace();
SwingUtilities.invokeLater(() -> {
setStatus("Error fetching mods: " + e.getMessage());
fetchModsBtn.setEnabled(true);
});
}
});
}
private void downloadSelectedMods() {
List<RemoteMod> selectedMods = modsList.getSelectedValuesList();
setStatus("Downloading " + selectedMods.size() + " mod(s)...");
Executors.newSingleThreadExecutor().submit(() -> {
int successCount = 0;
for (RemoteMod mod : selectedMods) {
try {
File targetFile = new File(downloadDir, mod.name);
if (targetFile.exists()) {
// skip existing
continue;
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(mod.downloadUrl))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() == 200) {
try (InputStream in = response.body();
FileOutputStream fos = new FileOutputStream(targetFile)) {
in.transferTo(fos);
}
successCount++;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
final int downloaded = successCount;
SwingUtilities.invokeLater(() ->
setStatus("Downloaded " + downloaded + " mod(s)."));
});
}
private void chooseDownloadDirectory() {
JFileChooser chooser = new JFileChooser(downloadDir);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = chooser.showOpenDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
File dir = chooser.getSelectedFile();
if (dir.exists() && dir.isDirectory()) {
downloadDir = dir;
downloadDirField.setText(downloadDir.getAbsolutePath());
setStatus("Download folder set to: " + downloadDir.getAbsolutePath());
} else {
setStatus("Invalid directory selected.");
}
}
}
private void setStatus(String message) {
statusLabel.setText(message);
}
private static class RemoteMod {
public final String name;
public final String downloadUrl;
public RemoteMod(String name, String downloadUrl) {
this.name = name;
this.downloadUrl = downloadUrl;
}
@Override
public String toString() {
return name;
}
}
}
also show download meter when downloading files
package org.nsomatrix.ui;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
public class ModsPanel extends JPanel {
private final DefaultListModel<RemoteMod> remoteModsModel = new DefaultListModel<>();
private final JList<RemoteMod> modsList;
private final JButton fetchModsBtn;
private final JButton downloadSelectedBtn;
private final JComboBox<String> sourceSelector;
private final JTextField downloadDirField;
private final JButton chooseDownloadDirBtn;
private final JLabel statusLabel;
private final JTextField searchField;
private final JPanel emptyStatePanel;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private File downloadDir = new File(System.getProperty("user.home"), "Downloads/mods");
// Keep a master list of all mods fetched (unfiltered)
private final List<RemoteMod> allMods = new ArrayList<>();
// Sources and their data URLs
private final String GITHUB_API_URL = "https://api.github.com/repos/cloudkore/matrix/contents/data/MODs";
private final String INTERNET_ARCHIVE_METADATA_URL = "https://archive.org/metadata/nsomtxmods";
public ModsPanel() {
setLayout(new BorderLayout(10, 10));
setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel titleLabel = new JLabel("Mods");
Font titleFont = UIManager.getFont("Label.font").deriveFont(Font.BOLD, 18f);
titleLabel.setFont(titleFont);
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(titleLabel, BorderLayout.NORTH);
// Search bar
searchField = new JTextField(30);
searchField.setToolTipText("Search mods...");
searchField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void removeUpdate(DocumentEvent e) {
filterMods();
}
@Override
public void changedUpdate(DocumentEvent e) {
filterMods();
}
});
// Top panel with source selector and search
JPanel topPanel = new JPanel(new BorderLayout(5, 5));
JPanel sourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
sourcePanel.add(new JLabel("Source:"));
sourceSelector = new JComboBox<>(new String[]{"GitHub", "Internet Archive"});
sourcePanel.add(sourceSelector);
topPanel.add(sourcePanel, BorderLayout.WEST);
topPanel.add(searchField, BorderLayout.CENTER);
add(topPanel, BorderLayout.PAGE_START);
modsList = new JList<>(remoteModsModel);
modsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modsList.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
if (value instanceof RemoteMod) {
label.setText(((RemoteMod) value).name);
}
return label;
}
});
JScrollPane scrollPane = new JScrollPane(modsList);
// Create empty placeholder panel
emptyStatePanel = new JPanel();
emptyStatePanel.setLayout(new BoxLayout(emptyStatePanel, BoxLayout.Y_AXIS));
emptyStatePanel.setOpaque(false);
emptyStatePanel.setBorder(new EmptyBorder(50, 20, 20, 20));
JLabel placeholderLabel = new JLabel(" Select Source to fetch MODs");
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 22f)); // big and bold
placeholderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
placeholderLabel.setBorder(new EmptyBorder(20, 0, 0, 0));
emptyStatePanel.add(placeholderLabel);
// Overlay for empty state on top of scroll pane
JPanel overlayPanel = new JPanel();
overlayPanel.setLayout(new OverlayLayout(overlayPanel));
overlayPanel.add(emptyStatePanel);
overlayPanel.add(scrollPane);
add(overlayPanel, BorderLayout.CENTER);
// Bottom panel with buttons, download dir and status
JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
fetchModsBtn = new JButton("Fetch MODs");
fetchModsBtn.addActionListener(e -> fetchMods());
downloadSelectedBtn = new JButton("Download");
downloadSelectedBtn.setEnabled(false);
downloadSelectedBtn.addActionListener(e -> downloadSelectedMods());
buttonsPanel.add(fetchModsBtn);
buttonsPanel.add(downloadSelectedBtn);
bottomPanel.add(buttonsPanel, BorderLayout.NORTH);
JPanel downloadDirPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
downloadDirField = new JTextField(downloadDir.getAbsolutePath(), 30);
chooseDownloadDirBtn = new JButton("Choose Download Folder");
chooseDownloadDirBtn.addActionListener(e -> chooseDownloadDirectory());
downloadDirPanel.add(new JLabel("Download Folder:"));
downloadDirPanel.add(downloadDirField);
downloadDirPanel.add(chooseDownloadDirBtn);
bottomPanel.add(downloadDirPanel, BorderLayout.CENTER);
statusLabel = new JLabel(" ");
statusLabel.setForeground(Color.GRAY);
bottomPanel.add(statusLabel, BorderLayout.SOUTH);
add(bottomPanel, BorderLayout.SOUTH);
modsList.addListSelectionListener(e -> downloadSelectedBtn.setEnabled(!modsList.isSelectionEmpty()));
remoteModsModel.addListDataListener(new javax.swing.event.ListDataListener() {
@Override
public void intervalAdded(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void intervalRemoved(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
@Override
public void contentsChanged(javax.swing.event.ListDataEvent e) {
updateEmptyStateVisibility();
}
});
updateEmptyStateVisibility();
try {
if (!Files.exists(downloadDir.toPath())) {
Files.createDirectories(downloadDir.toPath());
}
} catch (IOException ex) {
setStatus("Failed to create download directory.");
}
}
private void updateEmptyStateVisibility() {
emptyStatePanel.setVisible(remoteModsModel.isEmpty());
}
private void filterMods() {
String filter = searchField.getText().trim().toLowerCase();
remoteModsModel.clear();
if (filter.isEmpty()) {
allMods.forEach(remoteModsModel::addElement);
} else {
allMods.stream()
.filter(mod -> mod.name.toLowerCase().contains(filter))
.forEach(remoteModsModel::addElement);
}
}
private void fetchMods() {
setStatus("Fetching mod list...");
allMods.clear();
remoteModsModel.clear();
setUIEnabled(false);
String source = (String) sourceSelector.getSelectedItem();
String apiUrl = "Internet Archive".equals(source) ? INTERNET_ARCHIVE_METADATA_URL : GITHUB_API_URL;
executor.submit(() -> {
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Accept", "application/vnd.github.v3+json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
SwingUtilities.invokeLater(() -> {
setStatus("Failed to fetch mods: HTTP " + response.statusCode());
setUIEnabled(true);
});
return;
}
ObjectMapper mapper = new ObjectMapper();
List<RemoteMod> fetchedMods = new ArrayList<>();
if ("Internet Archive".equals(source)) {
JsonNode root = mapper.readTree(response.body());
JsonNode filesArray = root.get("files");
if (filesArray != null && filesArray.isArray()) {
for (JsonNode fileNode : filesArray) {
String name = fileNode.get("name").asText();
if (name.toLowerCase().endsWith(".jar")) {
String downloadUrl = "https://archive.org/download/nsomtxmods/" + name;
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
} else {
JsonNode root = mapper.readTree(response.body());
for (JsonNode node : root) {
String name = node.get("name").asText();
String downloadUrl = node.get("download_url").asText();
if (name.toLowerCase().endsWith(".jar")) {
fetchedMods.add(new RemoteMod(name, downloadUrl));
}
}
}
SwingUtilities.invokeLater(() -> {
allMods.clear();
allMods.addAll(fetchedMods);
filterMods();
setStatus("Fetched " + fetchedMods.size() + " mods from " + source);
setUIEnabled(true);
});
} catch (Exception e) {
e.printStackTrace();
SwingUtilities.invokeLater(() -> {
setStatus("Error fetching mods: " + e.getMessage());
setUIEnabled(true);
});
}
});
}
private void downloadSelectedMods() {
List<RemoteMod> selectedMods = modsList.getSelectedValuesList();
// Validate download directory first
if (!downloadDir.exists() || !downloadDir.isDirectory() || !downloadDir.canWrite()) {
setStatus("Download directory is invalid or not writable.");
return;
}
setUIEnabled(false);
statusLabel.setText("Downloading 0 of " + selectedMods.size() + " mod(s)...");
JProgressBar progressBar = new JProgressBar(0, selectedMods.size());
progressBar.setStringPainted(true);
// Show progress bar below the status label temporarily
SwingUtilities.invokeLater(() -> {
((BorderLayout) getLayout()).addLayoutComponent(progressBar, BorderLayout.SOUTH);
add(progressBar, BorderLayout.SOUTH);
revalidate();
repaint();
});
executor.submit(() -> {
int successCount = 0;
int progress = 0;
List<String> failedMods = new ArrayList<>();
for (RemoteMod mod : selectedMods) {
try {
File targetFile = new File(downloadDir, mod.name);
if (targetFile.exists()) {
// skip existing
progress++;
final int prog = progress;
SwingUtilities.invokeLater(() -> {
progressBar.setValue(prog);
progressBar.setString("Downloaded " + prog + " of " + selectedMods.size() + " mod(s)...");
});
continue;
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(mod.downloadUrl))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() == 200) {
try (InputStream in = response.body();
FileOutputStream fos = new FileOutputStream(targetFile)) {
in.transferTo(fos);
}
successCount++;
} else {
failedMods.add(mod.name);
}
} catch (Exception ex) {
ex.printStackTrace();
failedMods.add(mod.name);
}
progress++;
final int prog = progress;
SwingUtilities.invokeLater(() -> {
progressBar.setValue(prog);
progressBar.setString("Downloaded " + prog + " of " + selectedMods.size() + " mod(s)...");
});
}
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
setStatus("Downloaded " + successCount + " mod(s)."
+ (failedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", failedMods))));
setUIEnabled(true);
});
});
}
private void chooseDownloadDirectory() {
JFileChooser chooser = new JFileChooser(downloadDir);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = chooser.showOpenDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
File dir = chooser.getSelectedFile();
if (dir.exists() && dir.isDirectory()) {
downloadDir = dir;
downloadDirField.setText(downloadDir.getAbsolutePath());
setStatus("Download folder set to: " + downloadDir.getAbsolutePath());
} else {
setStatus("Invalid directory selected.");
}
}
}
private void setStatus(String message) {
statusLabel.setText(message);
}
private void setUIEnabled(boolean enabled) {
fetchModsBtn.setEnabled(enabled);
sourceSelector.setEnabled(enabled);
searchField.setEnabled(enabled);
downloadSelectedBtn.setEnabled(enabled && !modsList.isSelectionEmpty());
chooseDownloadDirBtn.setEnabled(enabled);
downloadDirField.setEnabled(enabled);
modsList.setEnabled(enabled);
}
@Override
public void removeNotify() {
super.removeNotify();
executor.shutdownNow(); // clean up executor thread when panel removed
}
private static class RemoteMod {
public final String name;
public final String downloadUrl;
public RemoteMod(String name, String downloadUrl) {
this.name = name;
this.downloadUrl = downloadUrl;
}
@Override
public String toString() {
return name;
}
}
}
What’s new/changed:
ExecutorService executor is a single thread pool reused for fetching and downloading tasks.
setUIEnabled(boolean) disables/enables inputs so no concurrent UI operations can conflict while fetching/downloading.
Download directory verified before starting downloads.
Added a JProgressBar dynamically, showing current progress with text.
Status label updates after each file to indicate progress.
If files failed to download, their names are listed in the final status message.
The progress bar is removed on completion.
removeNotify() overridden to shut down executor (prevents potential thread leaks).
Uses java.nio.file.Files.createDirectories() for creation of download folder with exception handling.
Fonts for title and placeholder label use platform defaults.
This approach makes downloads visible in real-time, disables input controls for consistent state, reports success and failures clearly, and improves resource handling.
If you'd like help polishing UI layout for the progress bar or further UX improvements, feel free to ask!
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
final int finalSuccessCount = successCount;
final List<String> finalFailedMods = new ArrayList<>(failedMods);
setStatus("Downloaded " + finalSuccessCount + " mod(s)."
+ (finalFailedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", finalFailedMods))));
setUIEnabled(true);
});
BUT this is still inside the lambda, so it won't compile.
So the final fix is: declare final copies beforeSwingUtilities.invokeLater() call:
java
final int finalSuccessCount = successCount;
final List<String> finalFailedMods = new ArrayList<>(failedMods);
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
setStatus("Downloaded " + finalSuccessCount + " mod(s)."
+ (finalFailedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", finalFailedMods))));
setUIEnabled(true);
});
Full context for clarity - this snippet from your method:
java
executor.submit(() -> {
int successCount = 0;
int progress = 0;
List<String> failedMods = new ArrayList<>();
for (RemoteMod mod : selectedMods) {
// your download logic ...
}
final int finalSuccessCount = successCount;
final List<String> finalFailedMods = new ArrayList<>(failedMods);
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
setStatus("Downloaded " + finalSuccessCount + " mod(s)."
+ (finalFailedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", finalFailedMods))));
setUIEnabled(true);
});
});
Summary
Declare final copies of any local variables accessed inside lambdas before the lambda.
Pass those to the lambda instead of the mutable originals.
If you need the fully fixed method or other help, just ask!
private void downloadSelectedMods() {
List<RemoteMod> selectedMods = modsList.getSelectedValuesList();
// Validate download directory first
if (!downloadDir.exists() || !downloadDir.isDirectory() || !downloadDir.canWrite()) {
setStatus("Download directory is invalid or not writable.");
return;
}
setUIEnabled(false);
statusLabel.setText("Downloading 0 of " + selectedMods.size() + " mod(s)...");
JProgressBar progressBar = new JProgressBar(0, selectedMods.size());
progressBar.setStringPainted(true);
// Show progress bar below the status label temporarily
SwingUtilities.invokeLater(() -> {
((BorderLayout) getLayout()).addLayoutComponent(progressBar, BorderLayout.SOUTH);
add(progressBar, BorderLayout.SOUTH);
revalidate();
repaint();
});
executor.submit(() -> {
int successCount = 0;
int progress = 0;
List<String> failedMods = new ArrayList<>();
for (RemoteMod mod : selectedMods) {
try {
File targetFile = new File(downloadDir, mod.name);
if (targetFile.exists()) {
// skip existing
progress++;
final int prog = progress;
SwingUtilities.invokeLater(() -> {
progressBar.setValue(prog);
progressBar.setString("Downloaded " + prog + " of " + selectedMods.size() + " mod(s)...");
});
continue;
}
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(mod.downloadUrl))
.build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
if (response.statusCode() == 200) {
try (InputStream in = response.body();
FileOutputStream fos = new FileOutputStream(targetFile)) {
in.transferTo(fos);
}
successCount++;
} else {
failedMods.add(mod.name);
}
} catch (Exception ex) {
ex.printStackTrace();
failedMods.add(mod.name);
}
progress++;
final int prog = progress;
SwingUtilities.invokeLater(() -> {
progressBar.setValue(prog);
progressBar.setString("Downloaded " + prog + " of " + selectedMods.size() + " mod(s)...");
});
}
final int finalSuccessCount = successCount;
final List<String> finalFailedMods = new ArrayList<>(failedMods);
SwingUtilities.invokeLater(() -> {
remove(progressBar);
revalidate();
repaint();
setStatus("Downloaded " + finalSuccessCount + " mod(s)."
+ (finalFailedMods.isEmpty() ? "" : (" Failed: " + String.join(", ", finalFailedMods))));
setUIEnabled(true);
});
});
}
What was changed:
Declared final int finalSuccessCount = successCount; and final List<String> finalFailedMods = new ArrayList<>(failedMods);before the invokeLater() lambda.
Used these final copies inside the lambda to avoid the "local variable referenced from lambda must be final or effectively final" compiler error.
If you want me to provide the full class updated with this fix or any other assistance, just say!