Java Swing 每次打开只运行一个实例,并激活任务栏里的程序

一、运行程序:

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import com.java.main.util.Const;

/**
 * @项目名称      OeeClient
 * @包名         com.java.main
 * @类名         App
 * @author      chenlin
 * @date        2013年9月14日 下午9:34:38
 * @version     1.0
 */@SuppressWarnings("all")
public class App {
    private Login loginFrame; // 窗体
    private SystemTray tray; // 系统托盘
    private OeeServer server; // 服务端socket

    public App() {
        init();
    }

    private void init() {
        // 如果当前操作系统不支持系统托盘,则退出
        if (!SystemTray.isSupported()) {
            JOptionPane.showMessageDialog(null, "对不起,当前操作系统不支持系统托盘!");
            System.exit(0);
        }
        tray = SystemTray.getSystemTray();
        Image image = null;
        try {
            image = ImageIO.read(new File(Const.IMAGE_PATH));
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            System.exit(0);
        }
        final TrayIcon trayIcon = new TrayIcon(image);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            System.exit(0);
        }
        PopupMenu menu = new PopupMenu();
        MenuItem mi = new MenuItem("Exit");
        mi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginFrame.setVisible(false);
                loginFrame.dispose();
                loginFrame = null;
                tray.remove(trayIcon);
                tray = null;
                server.closeServer();
                System.exit(0);
            }
        });
        menu.add(mi);
        trayIcon.setPopupMenu(menu);

        loginFrame = new Login();
        //loginFrame.setSize(new Dimension(200, 200));
        loginFrame.setVisible(true);
    }

    /**
     * 显示/隐藏 主窗体
     * */
    public void showHideFrame(boolean isVisible) {
        loginFrame.setVisible(isVisible);
        loginFrame.setExtendedState(Login.NORMAL);
    }

    /**
     * 注入server对象,关闭server时使用
     * 
     * @param server
     */
    public void setServerSocket(OeeServer server) {
        this.server = server;
    }

    // 检查是否获得锁,true:获得锁,说明是第一次执行;false:没有取得锁,说明已经有一个程序在执行
    public static boolean checkLock() {
        FileLock lock = null;
        RandomAccessFile r = null;
        FileChannel fc = null;
        try {
            // 在临时文件夹创建一个临时文件,锁住这个文件用来保证应用程序只有一个实例被创建.
            File sf = new File(System.getProperty("java.io.tmpdir") + "lock.single");
            sf.deleteOnExit();
            sf.createNewFile();
            r = new RandomAccessFile(sf, "rw");
            fc = r.getChannel();
            lock = fc.tryLock();
            if (lock == null || !lock.isValid()) {
                // 如果没有得到锁,则程序退出.
                // 没有必要手动释放锁和关闭流,当程序退出时,他们会被关闭的.
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) {
        // 检查文件锁,确保只有一个实例运行
        if (!checkLock()) {
            // 告知上一个程序激活主窗口
            try {
                new Socket(InetAddress.getLocalHost(), 60098);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 退出当前程序
            System.exit(0);
        }

        App app = new App();
        new OeeServer(app);
    }

    static class OeeServer {
        private ServerSocket server;// 当前的socket
        private App app; // 保存的前一个托盘实例

        public OeeServer(App app) {
            this.app = app;
            app.setServerSocket(this);
            initServerSocket();
        }

        private void initServerSocket() {
            try {
                server = new ServerSocket(60098);
                while (true) {
                    if (server.isClosed()) {
                        break;
                    }
                    // 如果监听到一个socket连接,说明程序启图再次打开一个实例,此时显示前一个窗体
                    Socket socket = server.accept();
                    app.showHideFrame(true);
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void closeServer() {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、登陆窗口

package com.java.main;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import org.apache.commons.lang.StringUtils;

import com.java.main.bean.User;
import com.java.main.helper.ExcelHelper;
import com.java.main.util.AppMain;
import com.java.main.util.BaseUtil;
import com.java.main.util.Const;
import com.java.main.util.RoundBorder;
import commontools.PropertiesTools;

/**
 * 主面板
 * 
 * @author chen.lin
 * 
 */
@SuppressWarnings("all")
public class Login extends JFrame {
    private static final long serialVersionUID = -4904979443156290518L;
    private JPanel contentPane;
    private int mWidth = 365;
    private int mHeight = 270;
    private JButton mBtnLogin;
    private Font mBoldFont;
    private JButton mBtnCancel;
    private JTextField mTextUsername;
    private JPasswordField mTextPasword;

    public Login() {
        super();
        initMainPanel();
        initEvents();
        scanProcessInfo();
        getRootPane().setDefaultButton(mBtnLogin);
    }

    /**
     * 在开机启动时,扫描
     */
    private void scanProcessInfo() {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                ExcelHelper.getInstance().ScanProcessInfo(Login.this);
            }
        };

        String timeStr = PropertiesTools.readValue(Const.CONFIG_PATH, Const.PROP_INTERVALTIME);
        if (!StringUtils.isEmpty(timeStr) && BaseUtil.isInteger(timeStr)) {
            int time = Integer.parseInt(timeStr);
            timer.schedule(task, 60 * 1000, time * 60 * 1000);
        }
    }

    private void initEvents() {
        mBtnLogin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                login();
            }

        });
        mBtnCancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Login.this.setVisible(false);
            }
        });

        this.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    login();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }

        });
    }

    private void login() {
        String username = mTextUsername.getText();
        if (StringUtils.isEmpty(username)) {
            AppMain.showError(Login.this, "用户名称不能为空!");
            return;
        }

        String password = mTextPasword.getText();
        if (StringUtils.isEmpty(password)) {
            AppMain.showError(Login.this, "用户密码不能为空!");
            return;
        }

        String loginUsername = PropertiesTools.readValue(Const.CONFIG_PATH, Const.LOGIN_USERNAME);
        String loginPassword = PropertiesTools.readValue(Const.CONFIG_PATH, Const.LOGIN_PASSWORD);
        if (!username.equals(loginUsername) || !password.equals(loginPassword)) {
            AppMain.showError(Login.this, "用户名称或密码错误!");
            return;
        }

        User currentUser = new User(loginUsername, loginPassword);
        AppMain.setCurrentUser(currentUser);

        Main dialog = new Main();
        dialog.show(true);
        Login.this.setVisible(false);
    }

    // 重写这个方法
    @Override
    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING)
            return; // 直接返回,阻止默认动作,阻止窗口关闭
        super.processWindowEvent(e); // 该语句会执行窗口事件的默认动作(如:隐藏)
    }

    /**
     * 初始化主面板
     */
    private void initMainPanel() {
        setResizable(false);
        mBoldFont = new Font("宋体", Font.PLAIN, 12);
        setFont(mBoldFont);

        setTitle("OEE主界面");
        setIconImage(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // 得到屏幕的尺寸
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;
        // 高度
        setBounds(screenSize.width / 2 - mWidth / 2, screenSize.height / 2 - mHeight / 2, mWidth, mHeight);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        getContentPane().setLayout(null);

        JLabel jLabel0 = new JLabel("用户名称:");
        jLabel0.setHorizontalAlignment(SwingConstants.RIGHT);
        jLabel0.setBounds(10, 60, 117, 15);
        contentPane.add(jLabel0);
        mTextUsername = new JTextField();
        jLabel0.setLabelFor(mTextUsername);
        mTextUsername.setBounds(137, 55, 160, 25);
        contentPane.add(mTextUsername);

        JLabel jLabel1 = new JLabel("用户密码:");
        jLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
        jLabel1.setBounds(10, 95, 117, 15);
        contentPane.add(jLabel1);
        mTextPasword = new JPasswordField();
        jLabel1.setLabelFor(mTextPasword);
        mTextPasword.setBounds(137, 90, 160, 25);
        contentPane.add(mTextPasword);

        mBtnLogin = new JButton("登陆");
        mBtnLogin.setFont(mBoldFont);
        mBtnLogin.setFocusable(false);
        mBtnLogin.setBorder(new RoundBorder());
        mBtnLogin.setBounds(137, 130, 60, 27);
        contentPane.add(mBtnLogin);

        mBtnCancel = new JButton("退出");
        mBtnCancel.setFont(mBoldFont);
        mBtnCancel.setFocusable(false);
        mBtnCancel.setBorder(new RoundBorder());
        mBtnCancel.setBounds(210, 130, 60, 27);
        contentPane.add(mBtnCancel);

        setSize(mWidth, mHeight);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Login frame = new Login();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

}

—————————————————–
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
请先拍 购买地址, 下载请用百度盘
目录如下:
01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)

01高级架构师四十二个阶段高内容:
这里写图片描述
这里写图片描述
—————————————————–

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值