Java桌面程序多次被打开时显示已运行的程序的窗口

来源:互联网 发布:编程对电脑配置的要求 编辑:程序博客网 时间:2024/05/16 23:41

  在“单例”的例子的基础下,自己经过多次的测试和查找API,对Swing的API也不是很熟悉,有些想要的方法没找到,网上也没查找到资料,就简单的实现了这么一个小功能,只是性能的问题暂时不在考虑范围。可根据实际情况优化。

 

  单例控制类:

import java.net.ServerSocket;import java.net.Socket;import javax.swing.JFrame;/** * @author WangW *  */public class InstanceControl implements Runnable {private JFrame frame;public InstanceControl(JFrame frame) {this.frame = frame;}/** * 原理:先申请连接,如果不成功,则创建一个服务端,程序就创建了一个示例。 *   下次再运行的时候,又连接,如果连接上了,则证明已经创建了此端口的一个服务, *   证明有实例存在,就退出。同时已创建的服务如果接受到了连接,则可做一些事情。 */public void run() {try {new Socket("127.0.0.1", 12333);// 创建socket,连接12333端口System.exit(0); // 连接成功,说明有实例存在,则退出} catch (Exception e) {}try {ServerSocket server = new ServerSocket(12333);// 创建socket,连接12333端口while (true) {Socket socket = server.accept(); // 接受连接请求if (null != socket) {if (frame.isVisible()) {frame.setExtendedState(JFrame.NORMAL);if (!frame.isFocused()) {frame.setAlwaysOnTop(true);frame.setAlwaysOnTop(false);}} else {frame.setVisible(true);}}}} catch (Exception e) {e.printStackTrace();}}}

 

测试类:

import javax.swing.JFrame;/** * @author WangW * */public  class MainSingle extends JFrame{private static final long serialVersionUID = 7298654510352964995L;public MainSingle() {setTitle("Single");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(200, 100);}public static void main(String[] args) {MainSingle frame = new MainSingle();InstanceControl ic = new InstanceControl(frame);Thread t = new Thread(ic);t.start();frame.setVisible(true);}}


 


原创粉丝点击