java - 抓住双击托盘中图标的事件

时间:2011-06-09 07:39:42

标签: java swing

当我双击托盘图标时,我想让我的表单可见? 如何双击图标? 感谢。

6 个答案:

答案 0 :(得分:9)

尝试将MouseListener与

一起使用
     public void mousePressed( MouseEvent e ) {
        if(e.getClickCount() >= 2){
            //do something
        }
     }

答案 1 :(得分:7)

嗯,基本上所有的帖子都是正确的......但是对于DoubleMouseClick的corect输出必须包装到javax.swing.Timer

例如

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ClickListener extends MouseAdapter implements ActionListener {

    private final static int clickInterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
    private MouseEvent lastEvent;
    private Timer timer;

    public ClickListener() {
        this(clickInterval);
    }

    public ClickListener(int delay) {
        timer = new Timer(delay, this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        /*if (e.getClickCount() > 2) {
            return;
        }
        lastEvent = e;
        if (timer.isRunning()) {
            timer.stop();
            doubleClick(lastEvent);
        } else {
            timer.restart();
        }*/

        if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
            System.out.println("double");
            timer.stop();
        } else {
            timer.restart();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        timer.stop();
        singleClick(lastEvent);
    }

    public void singleClick(MouseEvent e) {
    }

    public void doubleClick(MouseEvent e) {
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Double Click Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addMouseListener(new ClickListener() {

            @Override
            public void singleClick(MouseEvent e) {
                System.out.println("single");
            }

            @Override
            public void doubleClick(MouseEvent e) {
                System.out.println("double");
            }
        });
        frame.setPreferredSize(new Dimension(200, 200));
        frame.pack();
        frame.setVisible(true);
    }
}

但使用TrayIcon对SystemTray进行corerrect将添加ActionListener

例如

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

public class TrayIconDemo {

    public static void main(String[] args) {
        try {// Use an appropriate Look and Feel
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        UIManager.put("swing.boldMetal", Boolean.FALSE);// Turn off metal's use of bold fonts     
        SwingUtilities.invokeLater(new Runnable() {//Schedule a job for the event-dispatching thread: adding TrayIcon.

            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        if (!SystemTray.isSupported()) {//Check the SystemTray support
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon = new TrayIcon(createImage("Icon/failed.png", "tray icon"));
        final SystemTray tray = SystemTray.getSystemTray();
        MenuItem aboutItem = new MenuItem("About"); // Create a popup menu components
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        MenuItem errorItem = new MenuItem("Error");
        MenuItem warningItem = new MenuItem("Warning");
        MenuItem infoItem = new MenuItem("Info");
        MenuItem noneItem = new MenuItem("None");
        MenuItem exitItem = new MenuItem("Exit");
        popup.add(aboutItem); //Add components to popup menu
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);
        trayIcon.setPopupMenu(popup);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }
        trayIcon.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
            }
        });
        aboutItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "This dialog box is run from the About menu item");
            }
        });
        cb1.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                int cb1Id = e.getStateChange();
                if (cb1Id == ItemEvent.SELECTED) {
                    trayIcon.setImageAutoSize(true);
                } else {
                    trayIcon.setImageAutoSize(false);
                }
            }
        });
        cb2.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                int cb2Id = e.getStateChange();
                if (cb2Id == ItemEvent.SELECTED) {
                    trayIcon.setToolTip("Sun TrayIcon");
                } else {
                    trayIcon.setToolTip(null);
                }
            }
        });
        ActionListener listener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem) e.getSource();
                System.out.println(item.getLabel()); //TrayIcon.MessageType type = null;
                if ("Error".equals(item.getLabel())) {//type = TrayIcon.MessageType.ERROR  ;                  
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message", TrayIcon.MessageType.ERROR);
                } else if ("Warning".equals(item.getLabel())) {//type = TrayIcon.MessageType.WARNING;                    
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message", TrayIcon.MessageType.WARNING);
                } else if ("Info".equals(item.getLabel())) { //type = TrayIcon.MessageType.INFO;                   
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message", TrayIcon.MessageType.INFO);
                } else if ("None".equals(item.getLabel())) {//type = TrayIcon.MessageType.NONE;                    
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message", TrayIcon.MessageType.NONE);
                }
            }
        };
        errorItem.addActionListener(listener);
        warningItem.addActionListener(listener);
        infoItem.addActionListener(listener);
        noneItem.addActionListener(listener);
        exitItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
    }

    protected static Image createImage(String path, String description) {//Obtain the image URL
        URL imageURL = TrayIconDemo.class.getResource(path);
        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }

    private TrayIconDemo() {
    }
}

答案 2 :(得分:4)

使用MouseListener接口

public class MouseEventDemo ... implements MouseListener

并实施

public void mouseClicked(MouseEvent e) { }

您可以从int getClickCount()找到点击值,它会返回用户所做的快速连续点击次数(包括此事件)。例如,双击返回2.

答案 3 :(得分:3)

ActionListener actionListener = new ActionListener() {
    @Override
    public void actionPerformed( ActionEvent e ) {
      //Double click code here
    }
};

SystemTray tray = SystemTray.getSystemTray();
TrayIcon trayIcon = new TrayIcon(<icon stuff>);

trayIcon.addActionListener(actionListener);
tray.add(trayIcon);

这就是我的工作方式

答案 4 :(得分:2)

如果您打算为此编写自己的函数,请执行以下操作:

捕获鼠标单击事件,保持“long timeStamp”将其初始化为0L作为实例变量,

现在双击是在3秒或5秒内两次点击

so 
{
if (timeStamp == 0L) {

timeStamp = System.getCurrentTime(); //please chk the exact syntax of this... it gives       milli seconds

} else if ((timeStamp + 5000) <= System.getCurrentTime()) // here i am giving time     window of 5 sec = 5000 milli  seconds

{
//do ur double click code;
then set timeStamp back to 0;
timeStamp = 0L;

} else {
//its first click
timeStamp = System.getCurrentTime();

}
}

答案 5 :(得分:1)

trayIcon.addMouseListener(new java.awt.event.MouseAdapter() {

    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        if (evt.getClickCount() == 2) {
            setVisible(true);
            setExtendedState(JFrame.NORMAL);
        }
    }

});
tray.add(trayIcon);

这将完成这项工作。