【问题标题】:How do I add things to the system tray and add mouseOver() functionality?如何将东西添加到系统托盘并添加 mouseOver() 功能?
【发布时间】:2012-12-31 12:38:17
【问题描述】:

对不起,如果标题含糊不清,但这是我想要实现的。
这是Battery Care 软件图标化/最小化。当您将鼠标悬停在图标上时,您会看到图片中的窗口。
怎么能用 Java 实现呢?

【问题讨论】:

标签: java swing mouseevent mouseover system-tray


【解决方案1】:

这使用JPopupMenu 来显示点击信息,这不是最推荐的方法,因为很难布局其他组件...但您可以轻松地使用JWindow 代替...

public class SystemTrayTest {

  public static void main(String[] args) {
    if (SystemTray.isSupported()) {

      EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
          try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          } catch (Exception ex) {
          }
          try {
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JLabel("Charging (45%)", JLabel.CENTER));

            popup.add(new JLabel("Charging", new ImageIcon(ImageIO.read(SystemTrayTest.class.getResource("/battery_connection.png"))), JLabel.LEFT));
            popup.add(new JLabel("Power Saver", new ImageIcon(ImageIO.read(SystemTrayTest.class.getResource("/flash_yellow.png"))), JLabel.LEFT));

            popup.add(new JSeparator());

            JMenuItem exitMI = new JMenuItem("Exit");
            exitMI.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                System.exit(0);
              }
            });
            popup.add(exitMI);

            TrayIcon trayIcon = new TrayIcon(ImageIO.read(SystemTrayTest.class.getResource("/battery_green.png")), "Feel the power");
            trayIcon.addMouseListener(new MouseAdapter() {
              @Override
              public void mouseClicked(MouseEvent e) {
                popup.setLocation(e.getX(), e.getY());
                popup.setInvoker(popup);
                popup.setVisible(true);
              }
            });
            SystemTray.getSystemTray().add(trayIcon);
          } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
          }

        }
      });
    }

  }
}

更新了鼠标悬停支持

因为我忍不住要玩……

public class SystemTrayTest {

  public static void main(String[] args) {
    new SystemTrayTest();
  }

  public SystemTrayTest() {
    if (SystemTray.isSupported()) {

      EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
          try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          } catch (Exception ex) {
          }
          try {
            TrayIcon trayIcon = new TrayIcon(ImageIO.read(SystemTrayTest.class.getResource("/battery_green.png")), "Feel the power");
            MouseHandler mouseHandler = new MouseHandler();
            trayIcon.addMouseMotionListener(mouseHandler);
            trayIcon.addMouseListener(mouseHandler);
            SystemTray.getSystemTray().add(trayIcon);
          } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
          }
        }
      });
    }
  }

  public class MouseHandler extends MouseAdapter {

    private Timer popupTimer;
    private JWindow popup;
    private Point point;

    public MouseHandler() {
      popup = new JWindow();
      ((JComponent)popup.getContentPane()).setBorder(new LineBorder(Color.LIGHT_GRAY));
      popup.setLayout(new GridLayout(0, 1));
      popup.add(new JLabel("Charging (45%)", JLabel.CENTER));

      try {
        popup.add(new JLabel("Charging", new ImageIcon(ImageIO.read(getClass().getResource("/battery_connection.png"))), JLabel.LEFT));
        popup.add(new JLabel("Power Saver", new ImageIcon(ImageIO.read(getClass().getResource("/flash_yellow.png"))), JLabel.LEFT));
      } catch (IOException exp) {
        exp.printStackTrace();
      }
      popup.pack();

      popupTimer = new Timer(250, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
          if (point != null) {
            System.out.println(point);
            Rectangle bounds = getScreenViewableBounds(point);
            int x = point.x;
            int y = point.y;
            if (y < bounds.y) {
              y = bounds.y;
            } else if (y > bounds.y + bounds.height) {
              y = bounds.y + bounds.height;
            }
            if (x < bounds.x) {
              x = bounds.x;
            } else if (x > bounds.x + bounds.width) {
              x = bounds.x + bounds.width;
            }

            if (x + popup.getWidth() > bounds.x + bounds.width) {
              x = (bounds.x + bounds.width) - popup.getWidth();
            }
            if (y + popup.getWidth() > bounds.y + bounds.height) {
              y = (bounds.y + bounds.height) - popup.getHeight();
            }
            popup.setLocation(x, y);
            popup.setVisible(true);
          }
        }
      });
      popupTimer.setRepeats(false);

    }

    @Override
    public void mouseExited(MouseEvent e) {
      System.out.println("Stop");
      point = null;
      popupTimer.stop();
      popup.setVisible(false);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
      popupTimer.restart();
      point = e.getPoint();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
      System.exit(0);
    }
  }

  public static GraphicsDevice getGraphicsDeviceAt(Point pos) {

    GraphicsDevice device = null;

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice lstGDs[] = ge.getScreenDevices();

    ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);

    for (GraphicsDevice gd : lstGDs) {

      GraphicsConfiguration gc = gd.getDefaultConfiguration();
      Rectangle screenBounds = gc.getBounds();

      if (screenBounds.contains(pos)) {

        lstDevices.add(gd);

      }

    }

    if (lstDevices.size() == 1) {

      device = lstDevices.get(0);

    }

    return device;

  }

  public static Rectangle getScreenViewableBounds(Point p) {

    return getScreenViewableBounds(getGraphicsDeviceAt(p));

  }

  public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {

    Rectangle bounds = new Rectangle(0, 0, 0, 0);

    if (gd != null) {

      GraphicsConfiguration gc = gd.getDefaultConfiguration();
      bounds = gc.getBounds();

      Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

      bounds.x += insets.left;
      bounds.y += insets.top;
      bounds.width -= (insets.left + insets.right);
      bounds.height -= (insets.top + insets.bottom);

    }

    return bounds;

  }
}

【讨论】:

  • JWindow 基本上就像一个可以显示在屏幕上的JPanel,对吗?
  • 不,不是。 JWindow 更像是一个未经修饰的JFrameJFrame 延伸自JWindow
  • 我知道层次结构,只是在打个比方 :) 如果你还想再看一些 Java:stackoverflow.com/questions/14375338/…
【解决方案2】:

起初,我认为这相当简单 - 使用 addMouseListener() 将鼠标侦听器添加到 TrayIcon 并使用 mouseEntered() 和 mouseExitedEvents():

icon.addMouseListener(new MouseAdapter()
{
    @Override
    public void mouseEntered(MouseEvent e)
    {
        System.out.println("Mouse over icon");
    }

    @Override
    public void mouseExited(MouseEvent e)
    {
        System.out.println("Mouse leaving icon");
    }
});

但是,至少在我测试过的平台上(Windows 上的 Java 7u10)这不起作用 - 当我将鼠标光标悬停在托盘图标上时,没有生成任何事件。起作用的是MouseMotionListeneraddMouseMotionListener 方法:

icon.addMouseMotionListener(new MouseMotionAdapter()
{
    @Override
    public void mouseMoved(MouseEvent e)
    {
        System.out.println("Moving...");
    }
});

仅当鼠标悬停在图标上时才会在mouseMoved() 中生成事件。通过一些工作,这可用于在收到第一个事件后的一定延迟后显示JWindow,以模拟工具提示时间(您可以通过ToolTipManager.sharedInstance().getInitialDelay()之类的方式获取平台的工具提示显示时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多