我使用ServerSocket端口只运行我的Java Swing应用程序的一个实例,所以如果用户试图打开另一个程序实例,我会向他显示“另一个实例已经打开”的警告。这样工作正常,但我没有显示此消息,而是希望将焦点放在正在运行的应用程序本身上,就像某些程序一样(MSN Messenger),即使它已被最小化。
对于各种操作系统,是否有解决方案?
答案 0 :(得分:2)
由于您使用服务器套接字,我假设您使用java.net.BindException来检测您的应用程序是否已在运行。如果您启动第二个实例,您可以发送一条控制消息,指示您在退出之前将第一个应用程序规范化(如果最小化)。
if (msg == BRING_TO_FRONT ) {
frame.setState(Frame.NORMAL);
frame.toFront();
}
答案 1 :(得分:1)
我不知道这是否完全正确,但这是我用过的最终代码,对我来说效果很好:
public class Loader {
private static final int PORT = 9999;
private static ServerSocket serverSocket = null; // Server
private static Socket socket = null; // CLient
private static final String focusProgram = "FOCUS";
public static void main(String[] args) {
if( !isProgramRunning() ) {
Main main = new Main();
main.setVisible( true );
}
else {
System.exit( 2 );
}
}
private static boolean isProgramRunning() {
try {
serverSocket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1})); // Bind to localhost adapter with a zero connection queue.
SwingWorker<String, Void> anotherThread = new SwingWorker<String, Void>() { // Do some code in another normal thread.
@Override
public String doInBackground() { // This method is to execute a long code in the other thread in background.
serverSocketListener();
return "";
}
};
anotherThread.execute(); // Execute the other tread.
}
catch (BindException e) {
System.err.println("Already running.");
clientSocketListener();
return true;
}
catch (IOException e) {
System.err.println("Unexpected error.");
e.printStackTrace();
return true;
}
return false;
}
public static void serverSocketListener() { // Server socket
try {
System.out.println( "Listener socket opened to prevent any other program instance." );
socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if( in.readLine().equals( focusProgram ) ) { // Restore the opened instance however you want.
Global.getCurrentFrame().setState(Frame.NORMAL);
Global.getCurrentFrame().toFront();
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void clientSocketListener() { // Client socket
try{
socket = new Socket(InetAddress.getByAddress( new byte[] {127,0,0,1}), PORT );
PrintWriter out = new PrintWriter( socket.getOutputStream(), true );
out.println( focusProgram );
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}
}