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
Your EmuRunPanel class is a nicely structured Swing panel for managing a list of games (JAR files) to launch with different emulators. It supports adding/removing games, drag-and-drop of JAR files, persisting the list, and displaying last-played timestamps.
Below are some observations, suggestions, and explanations about your code that may help improve or extend functionality:
1. Drag and Drop Handling
You implemented drag and drop using DropTargetListener on both the panel and the list. It works well because both target components independently can accept drops.
You check if data flavor is supported and accept/reject accordingly.
You loop through all dropped files, launch all JARs, add new ones to the list, and save the updated list.
Suggestion:
You might want to defer launching games until after the entire drop event is processed, like adding the files to the list first, then separately launching them — this can improve responsiveness and make the UI consistent if you want to add a "Launch All" button later.
2. Storage Format and Location
Games are saved in a simple text file in the user’s home directory under .matrix_launcher_games.txt.
Each line stores the absolute path and last played timestamp separated by |.
This is simple and effective.
Consider:
Using JSON or another structured format like XML or properties to allow easier future extension (e.g., adding tags or other metadata).
Checking for race conditions or concurrency issues if saveGamesToStorage() might be called multiple times quickly (may not be a big concern in this UI-driven app).
3. GameEntry equals/hashCode
You override equals() and hashCode() to identify games by their underlying file. This is good for ensuring uniqueness in your list model.
4. Last Played Timestamp and Display
You track a last played timestamp for each game and display it using a SimpleDateFormat.
The cells render file name, size in KB, and last played.
This is user-friendly.
Possible improvements:
Add sorting options, e.g., sort by last played or name.
Add a tooltip showing full file path when hovering on the list.
Format size in MB if the file is large.
5. Buttons and UI Interactions
User
do you know microemu-cldc-2.0.4.jar microemu-javase-2.0.4.jar microemu-javase-swing-2.0.4.jar microemu-midp-2.0.4.jar midpapi20-2.0.4.jar
manish@manish-vostro153568:~/emu$
Assistant
Yes, I recognize these JAR files—these are components of MicroEmu, an open-source Java ME (Micro Edition) emulator implementation. Here's a quick rundown of what those JAR files likely represent:
MicroEmu Overview
MicroEmu is a Java ME emulator that allows running MIDP (Mobile Information Device Profile) applications (primarily J2ME mobile games and apps) on desktop platforms.
The JARs you listed
microemu-cldc-2.0.4.jar
Contains the CLDC (Connected Limited Device Configuration) implementation classes. CLDC defines the basic Java runtime environment for constrained devices (like old mobile phones).
microemu-midp-2.0.4.jar
Provides the MIDP 2.0 implementation classes. MIDP sits on top of CLDC and defines the APIs for UI, networking, and other mobile device features.
microemu-javase-2.0.4.jar
Implements the MicroEmu core for Java SE platform (desktop). This ties MicroEmu to desktop Java runtime.
microemu-javase-swing-2.0.4.jar
Provides the Swing-based UI components for MicroEmu on Java SE. This handles rendering the emulated device’s screen, handling inputs via mouse/keyboard, and other desktop interactions.
midpapi20-2.0.4.jar
This usually contains API stubs or additional compatibility layers for MIDP 2.0. Sometimes it's part of MicroEmu or related projects for interface definitions or API-level compatibility.
How They Relate
These JARs together implement a full Java ME emulator on desktop Java SE. For example, your emulator launcher might need all of these JARs on the classpath to run MicroEmu and emulate MIDP applications (J2ME JARs).
What Can You Do With Them?
Run J2ME MIDlets (Java ME apps/games) on your desktop.
Integrate MicroEmu as an emulator backend in your launcher.
Extend or modify MicroEmu to support additional features.
Usage Example (Command line):
To run a MIDlet with MicroEmu (assuming you have a MIDlet JAR file game.jar):
my current code launched a microemulator tab external , i have moved all the four files to libs folder , can you integrate microemu right into my launcher?
public class EmuRunPanel extends JPanel {
private static final File STORAGE_FILE = new File(System.getProperty("user.home"), ".matrix_launcher_games.txt");
code
Assistant
To integrate MicroEmu directly inside your launcher UI (i.e., embed MicroEmu emulator as a swing component instead of launching it externally), you need to create and embed MicroEmu’s MIDlet emulator component/view inside your Swing app.
1. What integration means here:
Instead of EmulatorLauncher.launch(...) spawning a separate process or window,
you instantiate MicroEmu’s classes in your application JVM,
create a component (e.g., a JPanel) that shows the MIDlet emulator screen,
add that component to your UI (e.g., as a tab or a dialog),
and control MicroEmu programmatically to load and run the selected JAR file.
2. MicroEmu Java SE Swing API
MicroEmu uses Swing, so it can be embedded.
According to MicroEmu's typical usage, the main class is com.microemu.app.ui.EmulatorFrame (the Swing JFrame to launch a MIDlet), or you can directly use EmulatorUI or related classes.
To embed, sometimes you will create an instance of an emulator panel or frame and embed its content pane inside your Swing container.
3. Steps to integrate into your launcher
I will show you how to:
Add a JTabbedPane to your launcher UI (or a dialog),
When launch is clicked, create a MicroEmu emulator panel for that JAR,
Add it as a new tab, showing the emulated MIDlet inside your launcher window,
Allow closing tabs (optional),
You must have MicroEmu jars in your classpath (libs/ folder).
4. Example code changes for EmuRunPanel.java:
First, add a JTabbedPane member to EmuRunPanel to hold emulator panels:
java
private final JTabbedPane emulatorTabPane = new JTabbedPane();
Add it to your panel, for example at the center bottom. To keep your existing list layout, add the tabbed pane below:
In constructor, after adding your overlayPanel (list) at CENTER:
java
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(overlayPanel, BorderLayout.CENTER);
centerPanel.add(emulatorTabPane, BorderLayout.SOUTH);
// Preferred height for emulatorTabPane, e.g. 400px height
emulatorTabPane.setPreferredSize(new Dimension(600, 400));
add(centerPanel, BorderLayout.CENTER);
User
can you give me updated EmuRunPanel.java which integrates microemu
public class EmuRunPanel extends JPanel {
private static final File STORAGE_FILE = new File(System.getProperty("user.home"), ".matrix_launcher_games.txt");
code
Assistant
Certainly! Below is your updated EmuRunPanel.java which integrates MicroEmu directly inside your launcher by embedding the MicroEmu emulator UI into a JTabbedPane inside your launcher panel.
What changed?
Added a JTabbedPane called emulatorTabPane at the bottom of the center panel to host emulator tabs.
Modified launchSelectedGame() to launch embedded MicroEmu emulator tabs instead of the external launcher.
Added createMicroEmuPanel(File midletJar) method to instantiate and run MicroEmu UI inside a JPanel.
Removed usage of EmulatorLauncher.launch() for launching MicroEmu (you can keep it for other emulators).
Important Notes Before Using
Add all MicroEmu jars to your classpath (libs/*), e.g.:
microemu-cldc-2.0.4.jar
microemu-midp-2.0.4.jar
microemu-javase-2.0.4.jar
microemu-javase-swing-2.0.4.jar
This requires MicroEmu 2.x APIs — if your MicroEmu version is different, APIs may differ.
The embedded emulator size is fixed to 320x480 typical MIDP screen.
You may want to add tab closing or resizing controls later.
public class UI {
private final JFrame frame;
private final JPanel contentPanel;
private final HashMap<String, JButton> tabButtons = new HashMap<>();
private final JLabel statusBar = new JLabel(" Ready.");
private final Preferences prefs;
code
Assistant
Your current UI.java mostly manages the overall application window, tab switching, theme, and status bar. Integrating MicroEmu inside EmuRunPanel as an embedded tab component does not require major changes here because:
You already expose getSelectedEmulator() which returns the selected emulator string,
Your EmuRunPanel uses appUI.getSelectedEmulator() to decide how to launch the game,
So to trigger embedded MicroEmu, just make sure the emulator name matches what EmuRunPanel expects.
What you should do in UI.java for MicroEmu integration:
Set the default emulator name in preferences to "microemu" (or "MicroEmulator" depending on your EmuRunPanel check)
In the existing method:
java
public String getSelectedEmulator() {
return prefs.get("app_emulator", "Microemulator"); // default emulator name
}
You can change "Microemulator" to "microemu" or "microemu" to exactly match ignoring case.
Add an option or UI to select emulator (if it doesn’t exist)
If you want users to be able to pick between MicroEmu and other emulators, you should have such a selector somewhere (e.g., dropdown in settings panel). Then save that preference as app_emulator.
Example: If you want MicroEmu by default, just modify the default in getSelectedEmulator():
java
public String getSelectedEmulator() {
return prefs.get("app_emulator", "microemu"); // lowered for easy comparison
}
Optional: Add emulator chooser UI
If you want a combo box to pick emulator in SettingsPanel, implement that there and update stored prefs "app_emulator" accordingly.
No other changes are needed in UI.java because:
The emulator launching is handled in EmuRunPanel based on this emulator name,
Display and tab switching won’t be affected,
Themes and status bar stay the same.
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/EmuRunPanel.java:4: error: package com.microemu.app.ui does not exist
import com.microemu.app.ui.EmulatorUI;
^
/home/manish/IdeaProjects/HelloWorldGUI/src/main/java/org/nsomatrix/EmuRunPanel.java:275: error: cannot find symbol
EmulatorUI emulatorUI = new EmulatorUI();
^
symbol: class EmulatorUI
location: class EmuRunPanel
/home/manish/IdeaProjects/HelloWorldGUI/src/main/java/org/nsomatrix/EmuRunPanel.java:275: error: cannot find symbol
EmulatorUI emulatorUI = new EmulatorUI();
^
symbol: class EmulatorUI
location: class EmuRunPanel
3 errors
Try:
Check your code and dependencies to fix the compilation error(s)
Run with --scan to get full insights.
BUILD FAILED in 3s
1 actionable task: 1 executed
manish@manish-vostro153568:~/IdeaProjects/HelloWorldGUI
Assistant
The error means that the compiler cannot find the MicroEmu classes (com.microemu.app.ui.EmulatorUI) — which usually indicates the MicroEmu JARs are not properly on your project's compile classpath.
How to fix this:
1. Verify MicroEmu JARs are present in your project
You said you have these JARs in a libs folder:
microemu-cldc-2.0.4.jar
microemu-midp-2.0.4.jar
microemu-javase-2.0.4.jar
microemu-javase-swing-2.0.4.jar
Make sure these JAR files are physically inside your project folder, e.g.:
2. Add the MicroEmu JARs to your build system classpath
Since your error comes during compilation and you run from a Gradle task (:compileJava), you need to declare the MicroEmu jars as dependencies in your build.gradle.
For example, assuming you have a libs folder in the root project directory:
groovy
repositories {
// usual repositories if you want
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}
This tells Gradle to include all JARs in libs folder as implementation dependencies, allowing compilation and runtime access.
3. Refresh your Gradle project in IDE
In IntelliJ IDEA:
Click the Refresh button in the Gradle tool window to reload dependencies.
Rebuild your project.
In command line:
Run ./gradlew clean build --refresh-dependencies
4. Verify class availability
If still failing, unzip or open one of the MicroEmu jars (like microemu-javase-swing-2.0.4.jar) and check it contains the package com.microemu.app.ui and class EmulatorUI.class.
5. Fully qualified class name and imports
If MicroEmu version differs or your class isn't called EmulatorUI, adjust imports and code accordingly.
You must refresh or reimport Gradle in your IDE (IntelliJ IDEA):
Open Gradle tool window.
Click the Refresh button.
Wait until it syncs.
Build from command line
Try building from terminal with:
bash
./gradlew clean build --refresh-dependencies
Check if errors persist.
Double-check JAR contents
Verify that EmulatorUI class actually exists inside one of the MicroEmu jars (mostly likely microemu-javase-swing-2.0.4.jar):
bash
jar tf libs/microemu-javase-swing-2.0.4.jar | grep EmulatorUI
You should see something like:
code
com/microemu/app/ui/EmulatorUI.class
If you don’t see it, the MicroEmu version you have might not contain that class or uses a different package/class name.
If EmulatorUI does not exist
You might need to check the exact class MicroEmu exposes for embedding the emulator.
Sometimes projects rename or move classes between versions.
Possible alternative class: com.microemu.app.ui.EmulatorFrame or others.
Review MicroEmu documentation or JAR contents for the actual class to instantiate.
Verify imports in EmuRunPanel.java
Make sure you are importing the correct class. Example:
java
import com.microemu.app.ui.EmulatorUI;
Use the exact package and class name found inside jar.
Recap / next steps
Refresh Gradle in IDE.
Run ./gradlew clean build.
Confirm EmulatorUI exists in your jars.
Verify your import matches.
If EmulatorUI is missing, find the right MicroEmu class for embedding.
Restart your IDE if necessary.
If after all this you still have problems, please:
Post jar tf output for your MicroEmu jars (especially microemu-javase-swing-2.0.4.jar),
Share exact import statements you use in EmuRunPanel for MicroEmu,
I can help you find the correct embedding class based on your actual JAR contents.
User
manish@manish-vostro153568:/emujartflibs/microemu−javase−swing−2.0.4.jar∣grepEmulatorUIBasic.readAttributes(UnixFileAttributeViews.java:55)
at java.base/sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:148)
at java.base/sun.nio.fs.LinuxFileSystemProvider.readAttributes(LinuxFileSystemProvider.java:99)
at java.base/java.nio.file.Files.readAttributes(Files.java:1851)
at java.base/java.util.zip.ZipFileSource.get(ZipFile.java:CleanableResource.(ZipFile.java:717)
at java.base/java.util.zip.ZipFile.(ZipFile.java:251)
at java.base/java.util.zip.ZipFile.(ZipFile.java:180)
at java.base/java.util.zip.ZipFile.(ZipFile.java:151)
at jdk.jartool/sun.tools.jar.Main.list(Main.java:1503)
at jdk.jartool/sun.tools.jar.Main.run(Main.java:368)
at jdk.jartool/sun.tools.jar.Main.main(Main.java:1681)
manish@manish-vostro153568:/emujartfmicroemu−java
Assistant
The output jar tf microemu-javase-swing-2.0.4.jar | grep EmulatorUI shows no EmulatorUI class present in the microemu-javase-swing-2.0.4.jar file.
What this means:
The class com.microemu.app.ui.EmulatorUIdoes not exist in this MicroEmu version.
You cannot import or instantiate EmulatorUI as previously suggested.
MicroEmu’s API differs, or the class you want to use has a different name or packaging.
Next steps: Find the correct MicroEmu class to embed
MicroEmu 2.x typically uses EmulatorFrame or similar classes to launch MIDlets.
Try listing all classes in the jar and search for Emulator*:
bash
jar tf microemu-javase-swing-2.0.4.jar | grep Emulator
Do the same for all other MicroEmu jars, e.g.:
bash
jar tf microemu-javase-2.0.4.jar | grep Emulator
or
bash
jar tf microemu-midp-2.0.4.jar | grep Emulator
Common MicroEmu approach:
Run com.microemu.app.ui.EmulatorFrame class (extends JFrame), passing MIDlet JAR path.
This launches a separate window.
It appears MicroEmu does not provide a clean JPanel UI component to embed, at least not as a simple EmulatorUI class.
How to proceed with embedding:
Option A: Embed EmulatorFrame’s content pane in your panel
You can try:
java
EmulatorFrame frame = new EmulatorFrame(midletJar.getAbsolutePath());
Component emulatorContent = frame.getContentPane();
frame.setVisible(false); // Do not show the JFrame separately
// Add the emulatorContent component to your JPanel instead:
JPanel panel = new JPanel(new BorderLayout());
panel.add(emulatorContent, BorderLayout.CENTER);
Thanks for the info. From the jar contents you posted:
No EmulatorUI or EmulatorFrame classes.
The main MicroEmu class present is org.microemu.MicroEmulator in microemu-midp-2.0.4.jar.
There is also org.microemu.EmulatorContext in microemu-javase-2.0.4.jar.
What does this indicate?
You have a MicroEmu version that is Java package org.microemu (not com.microemu.app.ui), and the main entrypoint and emulator control is org.microemu.MicroEmulator.
How to launch a MIDlet programmatically with org.microemu.MicroEmulator?
Based on MicroEmu 2.x (org.microemu) API (reference: MicroEmu GitHub):
The class MicroEmulator has a static main method that launches the emulator.
You can create an instance of MicroEmulator and call its start method with the MIDlet's JAR URL or file.
Embedding or launching programmatically is possible with MicroEmulator instance.
Example to launch MIDlet JAR embedded:
java
import org.microemu.MicroEmulator;
import org.microemu.MIDletBridge;
import javax.microedition.midlet.MIDlet;
import java.io.File;
private JPanel createMicroEmuPanel(File midletJar) throws Exception {
// Instantiate MicroEmulator instance
MicroEmulator emulator = new MicroEmulator();
// Load the jar file URL
String url = midletJar.toURI().toURL().toString();
// Start the emulator
emulator.start(url);
// Get the displayable canvas (component) to embed
Component emulatorComponent = emulator.getDisplayComponent();
JPanel panel = new JPanel(new BorderLayout());
panel.add(emulatorComponent, BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(320, 480));
// Might want to add controls to stop emulator on tab close, etc.
return panel;
}
User
yes please give me full code
Assistant
Certainly! Below is your full updated EmuRunPanel.java integrating MicroEmu embedded inside your launcher via org.microemu.MicroEmulator, given your MicroEmu jars structure.
This version:
Adds a JTabbedPane to show emulator tabs inside the panel.
Uses MicroEmulator class to start MIDlets.
Embeds MicroEmulator's display component inside each tab.
Supports multiple running emulator tabs.
Keeps your existing UI for managing game JARs.
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/EmuRunPanel.java:298: error: MicroEmulator is abstract; cannot be instantiated
MicroEmulator emulator = new MicroEmulator();
^
/home/manish/IdeaProjects/HelloWorldGUI/src/main/java/org/nsomatrix/EmuRunPanel.java:302: error: cannot find symbol
emulator.start(url);
^
symbol: method start(String)
location: variable emulator of type MicroEmulator
/home/manish/IdeaProjects/HelloWorldGUI/src/main/java/org/nsomatrix/EmuRunPanel.java:304: error: cannot find symbol
Component display = emulator.getDisplayComponent();
^
symbol: method getDisplayComponent()
location: variable emulator of type MicroEmulator
3 errors
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
whats wrong?
Assistant
The errors say:
code
MicroEmulator is abstract; cannot be instantiated
emulator.start(url) method not found
emulator.getDisplayComponent() method not found
What this means:
The MicroEmulator class in org.microemu is abstract, so you cannot do new MicroEmulator().
The methods start(String) and getDisplayComponent() do not exist in that abstract class.
How to fix — use a concrete subclass or MicroEmu launcher pattern
1. Find concrete MicroEmulator subclass
The abstract MicroEmulator is a base class; MicroEmu provides concrete implementations you must instantiate.
Usually, it is:
MicroEmulator subclass called MIDletBridge or another class in the MicroEmu API,
or you need to create an implementation yourself with the right MIDP & CLDC configs.
2. Typical way MicroEmu is launched
MicroEmu sometimes uses a launcher class you run from main(); you don’t instantiate MicroEmulator directly.
The Launch button launches the selected game and updates the last played time.
Remove deletes the selected game.
Add Game opens a JFileChooser filtered to .jar files.
Disabled buttons if no selection.
You handle these appropriately.
6. Visual Appearance
You style buttons with custom background and foreground colors.
Empty state panel with drag-drop icon and instructions is a nice UX touch.
7. Minor Suggestions / Possible Enhancements
Exception Handling: Currently, you print stack traces and set a message label. You might enhance by showing an error dialog for severe exceptions.
Confirm Removal: For removing a game, consider a confirmation dialog to prevent accidental deletes.
Multi-selection: You have single selection only; you might allow multi-selection for bulk actions.
Sorting: When games are loaded, consider sorting them alphabetically or by last played.
File validity update: On load, if files no longer exist, you skip adding them but do not remove from storage file — you might clean the storage accordingly.
UI Responsiveness: If launching a game may take time, you might perform that in a background thread or task.
8. Code Cleanliness
Methods and inner classes are well organized.
You use lambda expressions and anonymous classes properly.
Overall, the code is clean and readable.
If you want me to help enhance or refactor a particular part, add new features, or fix specific issues, please let me know!
;
This assumes the main class of MicroEmu launcher is com.microemu.app.Main (usually it is).
If you plan to integrate MicroEmu into your Java launcher UI (like your EmuRunPanel), you would invoke MicroEmu’s launcher classes with a selected MIDlet JAR file and possibly pass parameters.
If you want help integrating MicroEmu into your existing Java Swing app (e.g., how to launch MIDlets via those jars or how to structure a MicroEmu-based emulator launcher), just let me know!
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;
}
}
}
Then, modify your launchSelectedGame() method to instantiate and embed MicroEmu's emulator:
java
private void launchSelectedGame() {
GameEntry selectedEntry = gamesList.getSelectedValue();
if (selectedEntry != null) {
File midletJar = selectedEntry.getFile();
try {
// Remove external launch via EmulatorLauncher.launch()
// Instead create MicroEmu embedded emulator panel
JPanel microEmuPanel = createMicroEmuPanel(midletJar);
// Add as new tab with file name
emulatorTabPane.addTab(midletJar.getName(), microEmuPanel);
emulatorTabPane.setSelectedComponent(microEmuPanel);
setMessage("Launching (embedded): " + midletJar.getName());
// Update last played timestamp
selectedEntry.setLastPlayedTimestamp(System.currentTimeMillis());
saveGamesToStorage();
gamesList.repaint();
} catch (Exception ex) {
ex.printStackTrace();
setMessage("Failed to launch MIDlet: " + ex.getMessage());
}
} else {
setMessage("No game selected to launch.");
}
}
5. Important: The createMicroEmuPanel(File midletJar) method
Here's an example implementation of embedding MicroEmu; it uses MicroEmu’s Swing classes.
java
import com.microemu.app.ui.EmulatorUI;
import com.microemu.device.impl.CommandListenerImpl;
import com.microemu.app.ui.EmulatorFrame;
import com.microemu.app.ui.EmulatorUI;
import javax.microedition.midlet.MIDlet;
...
private JPanel createMicroEmuPanel(File midletJar) throws Exception {
// EmulatorUI is the main component that runs MicroEmu MIDlet
EmulatorUI emulatorUI = new EmulatorUI();
// Load MIDlet from JAR file
// This step may vary depending on MicroEmu APIs. Usually:
// emulatorUI.load(midletJar.getAbsolutePath());
// Unfortunately, MicroEmu doesn't expose a simple 'load' method directly
// You may have to create an EmulatorFrame or similar, and embed its content pane.
// Let's use EmulatorFrame (which internally creates EmulatorUI) and embed it:
EmulatorFrame frame = new EmulatorFrame(midletJar.getAbsolutePath());
frame.setVisible(true); // You might omit this or set false if embedded.
// But ExplorerFrame extends JFrame which is not embeddable in JPanel.
// Solution: get content pane from EmulatorFrame and put in panel
// or better, create EmulatorUI and initialize it manually.
// Instead create EmulatorUI directly:
EmulatorUI ui = new EmulatorUI();
// Initialize the emulator UI with the MIDlet JAR
// This API may vary, example:
ui.load(midletJar.getAbsolutePath());
// This 'ui' is a JPanel and can be embedded
ui.setPreferredSize(new Dimension(320, 480)); // typical MIDP screen size
JPanel panel = new JPanel(new BorderLayout());
panel.add(ui, BorderLayout.CENTER);
return panel;
}
6. Notes on MicroEmu API
MicroEmu is not always trivial to embed because:
It expects to run as its own JFrame (EmulatorFrame).
The EmulatorUI is available but you may need to call methods like load(String jarPath) and start the emulator lifecycle manually.
If EmulatorUI class has a load() method or equivalent to start the MIDlet from a JAR file, use that.
7. Add MicroEmu JARs to your build and imports
Add these dependencies to your project classpath (libs folder):
If load() or start() don’t exist, you may need to look at MicroEmu source or javadoc to find exact usage.
9. Summary and Final Notes
You'll embed MicroEmu's emulator UI in the launcher.
Provide the MIDlet JAR path to MicroEmu emulator UI.
Add MicroEmu's UI component as a tab in your UI, allowing multiple emulators open.
You can implement closing tabs by adding popup menus or close buttons on tabs (optional).
10. What if APIs are unavailable or complicated?
If the MicroEmu API is not well designed for embedding (very common for emulator projects), you may do a different approach:
Launch MicroEmu in a separate JFrame, as before, but monitor its lifecycle and process it inside your app.
Or start MicroEmu as a separate process from your launcher.
If you want I can help you write the exact wrapper method with your current MicroEmu version & usage or help refactor your EmulatorLauncher for internal embedding. Just provide the MicroEmu API docs or relevant classes you want to use.
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.UI;
import com.microemu.app.ui.EmulatorUI;
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.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;
private final JTabbedPane emulatorTabPane = new JTabbedPane();
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);
// Create center panel and add overlayPanel and emulatorTabPane vertically
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(overlayPanel, BorderLayout.CENTER);
emulatorTabPane.setPreferredSize(new Dimension(600, 480)); // Enough height for emulator
centerPanel.add(emulatorTabPane, BorderLayout.SOUTH);
add(centerPanel, 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)) {
// Use embedded MicroEmu only if emulator selected is "microemu"
String emulator = appUI.getSelectedEmulator();
if ("microemu".equalsIgnoreCase(emulator)) {
launchEmbeddedMicroEmu(f);
} else {
// fallback to previous launcher external method
// Replace with your EmulatorLauncher or any other logic
// 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();
if ("microemu".equalsIgnoreCase(emulator)) {
launchEmbeddedMicroEmu(selectedEntry.getFile());
} else {
// fallback external launch
// 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 launchEmbeddedMicroEmu(File midletJar) {
try {
JPanel emulatorPanel = createMicroEmuPanel(midletJar);
emulatorTabPane.addTab(midletJar.getName(), emulatorPanel);
emulatorTabPane.setSelectedComponent(emulatorPanel);
} catch (Exception ex) {
ex.printStackTrace();
setMessage("Failed to launch MicroEmu: " + ex.getMessage());
}
}
private JPanel createMicroEmuPanel(File midletJar) throws Exception {
EmulatorUI emulatorUI = new EmulatorUI();
emulatorUI.load(midletJar.getAbsolutePath());
emulatorUI.start();
JPanel panel = new JPanel(new BorderLayout());
panel.add(emulatorUI, BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(320, 480)); // typical MIDP screen size
return panel;
}
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;
}
}
}
How to use
Make sure your UI class’s getSelectedEmulator() returns "microemu" (case-insensitive) to invoke this embedded emulator.
For other emulators, you can keep handling as before, e.g., calling your EmulatorLauncher.launch() method.
You can drag and drop .jar MIDlet files or add them manually, then launch to open embedded emulator tabs.
Emulator tabs appear below the list in your window, sizing at 320×480.
If you want tab close buttons or advanced features, let me know!
Bottom line: For your embedded MicroEmu integration to work seamlessly, just make sure your preference key "app_emulator" is set to "microemu" (all lowercase) or the exact string you check in EmuRunPanel ("microemu".equalsIgnoreCase(...)).
Example:
java
public String getSelectedEmulator() {
return prefs.get("app_emulator", "microemu");
}
No further change in UI.java is needed unless you want to add emulator selection UI controls.
If you want to implement an emulator dropdown or radio buttons in SettingsPanel and save emulator choice, I can help with that code too!
bash
jar tf libs/microemu-javase-swing-2.0.4.jar | grep EmulatorUI
Summary checklist:
Put MicroEmu jars in libs/ folder of your project.
Reference them in Gradle (build.gradle) via implementation fileTree(...).
Refresh/reimport Gradle project.
Rebuild.
Minimal build.gradle snippet example
groovy
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
// other dependencies, e.g., Swing is part of JDK, no extra needed
}
If you provide your build.gradle, I can help you adjust it properly.