Search code examples
javajdialog

How to check if JDialog is already opened in Java?


I am currently developing a digital clock widget. I have designed it using a JPanel form and add it to a JDialog. Here is the code.

static JDialog jDialog = new JDialog();

public static void main(String[] args)
{
   jDialog.setUndecorated(true);
   jDialog.add(new QuickLauncher());
   jDialog.pack();
   jDialog.setBackground(new Color(0, 255, 0, 0));
   jDialog.setLocationRelativeTo(null);
   jDialog.setVisible(true);
 }

The problem is when I run this program twice it opens two windows. So what I need is I need only one window to run and if I run the program again instead of running the program again, it needs to focus the application. I tried various examples and methods like isVisible() and isActive() but I can't figure it out how to fix this issue. I tried this also,

How to check if a jframe is opened?

Please anyone can help me? Thanks in advance.


Solution

  • There isn't a particularly clean way to do this. If you're able to use Java 9, you can use the new process API to get a list of all processes with ProcessHandle.allProcesses() and search for ones that match your program, but otherwise you'd need to resort to platform-dependent behavior.

    An alternative method (not requiring Java 9) would be to use a FileLock. You would create a file in a known location, then lock it (see above link). When the JVM shuts down, the lock will be released. When your program starts, you can then check whether the file is locked to determine whether your program is already running.