3

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.

Hasitha Jayawardana
  • 2,326
  • 4
  • 18
  • 36
  • 2
    FYI, I don't think the answers to the other question will help you: they're dealing with windows from the same application (i.e., running in the same JVM) - your question is about detecting a window created in a different instance. – Mike Harris Sep 04 '18 at 16:41
  • 1
    Requesting focus is a OS thing, two instances of a application will not share the instance you created in the code as you did, you need for example to write a file as a lock from the first application and check the lock on second run and display a message instead of creating a screen. – Marcos Vasconcelos Sep 04 '18 at 16:41
  • @MarcosVasconcelos How can I do that sir? write a lock file? Can you show some code snippet? – Hasitha Jayawardana Sep 04 '18 at 16:50
  • 1
    Write a file and check if its present or something like – Marcos Vasconcelos Sep 04 '18 at 17:08
  • @MarcosVasconcelos Ok sir I will give a try. – Hasitha Jayawardana Sep 04 '18 at 17:13

1 Answers1

1

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.

apetranzilla
  • 5,331
  • 27
  • 34