Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only one swing frame window opened at time

Tags:

java

swing

I developed one swing application but each time you run application new window is opened. I want that if one window is already opened other not allow to open.

like image 259
chetan Avatar asked Mar 27 '10 10:03

chetan


People also ask

How do you adjust the size of a swing frame?

setSize() and frame. pack() . You should use one of them at one time. Using setSize() you can give the size of frame you want but if you use pack() , it will automatically change the size of the frames according to the size of components in it.


3 Answers

Here is an example of a Java Single Application Instance:

A single instance application is one that only allows for 1 of the application to run no matter how many times the user tries to launch.

See also: A shorter example that does not notify the running instance.

The application tries to open a Socket on a specific port. In case another instance of your application is already running, opening the Socket fails.

This should already be sufficient for you, so you would not have to use the part of the code used to register new applications to the first one started.

Using a Socket has one great advantage compared to writing some sort of flag to the filesystem/registry/whatever:
It is removed even if your application crashes.

like image 91
Peter Lang Avatar answered Sep 23 '22 16:09

Peter Lang


It actually sounds like you only want one application open at a time. In which case why not take out a file lock or similar when the application runs, and check that on start up. The headache (of course) is clearing up that lock in the event that your program doesn't exit cleanly.

like image 35
Brian Agnew Avatar answered Sep 21 '22 16:09

Brian Agnew


My preferred solution is, as Peter Lang linked to, to use Sockets. When your app starts you can start a server socket listening for incoming connections on localhost (plus port of your choice). Before this happens in your code though you can try and make a connection to the server socket and if it is successful you know there is another instance already open, so you can quit the current instance with an appropriate message.

In your server socket implementation you can also add functionality that on receiving an incoming connection you actually force the current instance of the app to the foreground.

like image 32
DaveJohnston Avatar answered Sep 20 '22 16:09

DaveJohnston