setDefaultCloseOperation(HIDE_ON_CLOSE)和System TrayIcon

时间:2015-05-15 08:27:30

标签: java netbeans icons system tray

如何在关闭应用程序后显示我创建的java应用程序? 我的意思是我想要关闭我制作的应用程序,之后它仍然在后台进程(托盘)上运行,我做了,但是如何在双击托盘图标后再次显示应用程序(弹出)? 有人可以帮我吗?

public MainMenu(String access) {

    this.access = access;
    initComponents();
    customInit();
    this.setLocationRelativeTo(null);
    this.setExtendedState(this.MAXIMIZED_BOTH);
    requestJobList("ALL");  
    setDefaultCloseOperation(HIDE_ON_CLOSE);
    createReminder();
}



private void customInit(){

    joblistTable.setCellSelectionEnabled(rootPaneCheckingEnabled);

}

private void createReminder(){

  String icoPath = "C:/Users/user/Documents/NetBeansProjects/MOADesktopBaru/src/com/mayora/image/MOA.PNG";

  if(!SystemTray.isSupported()){
    System.out.println("System tray is not supported !!! ");
        return ;
    }
    //get the systemTray of the system
    SystemTray systemTray = SystemTray.getSystemTray();
    Image image = Toolkit.getDefaultToolkit().getImage(icoPath);

    //popupmenu
    PopupMenu trayPopupMenu = new PopupMenu();


    //1t menuitem for popupmenu
       MenuItem setting = new MenuItem("Setting");
        setting.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                SettingFrame SF = new SettingFrame ();
                jDesktopPane.add(SF);
                SF.show();                         
        }
        });     
        trayPopupMenu.add(setting);

        //2nd menuitem of popupmenu
        MenuItem close = new MenuItem("Close");
        close.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            System.exit(0);             
        }
        });
        trayPopupMenu.add(close);

        //setting tray icon
        TrayIcon trayIcon = new TrayIcon(image, "MOA Desktop", trayPopupMenu);
        //adjust to default size as per system recommendation 
        trayIcon.setImageAutoSize(true);

        trayIcon.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2)
        {
            initComponents();
            customInit();
            setExtendedState(MAXIMIZED_BOTH);
            requestJobList("ALL");  
            setDefaultCloseOperation(EXIT_ON_CLOSE);

         }
        }
    }); 

        try{
            systemTray.add(trayIcon);
        }catch(AWTException awtException){
            awtException.printStackTrace();
        }

}

1 个答案:

答案 0 :(得分:0)

我认为setDefaultCloseOperation(EXIT_ON_CLOSE);不应放在托盘图标监听器内。

要想通过双击其托盘图标再次显示您的应用,只需在此行中添加mouseClicked()方法:

setVisible(true);

请注意,您再次看到的是JFrame,因此如果您需要指定它,只需在setVisible(true)方法之前添加它即可。顺便说一句,由于应用程序已经执行(在后台),您不需要再次调用initComponents()方法。

另一个建议,不要使用mouseClicked()方法。请改用MouseListener Interface中的mousePressed()。为什么?有时您点击太快以至于应用检测到mouseDragged事件,因此点击不计算在内。如果您使用mousePressed(),则可以保证它同时检测到两次点击。