本文介绍了如何在Java中使用带有托盘图标的上下文菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用Netbeans开发Java应用程序,我想在系统任务栏上创建一个任务栏图标,当我右键单击任务栏图标时将显示一个弹出菜单.

I'm using Netbeans to develop a Java application and I want to create a tray icon at system tray and a popup menu will be display when I right click on tray icon.

我通过拖放创建了一个jframe和弹出菜单.

I have created a jframe and popup menu by drop and drap them.

但是我有一个问题.我的弹出菜单有2个菜单项(退出显示登录名),但是选中的菜单项没有突出显示,并且在单击菜单后项目,弹出菜单未关闭.

But I have a problem.My popup menu have 2 menu items (Exit and Show Login) but selected menu item is not high-lighted and after I click menu item, popup menu is not closed.

这是我的代码:

声明一些全局变量

SystemTray systemTray = null;
Image image = Toolkit.getDefaultToolkit().getImage("D:/key-16x16.png");

TrayIcon trayIcon = new TrayIcon(image);

创建并显示系统任务栏图标

Create and display system tray icon

 systemTray = SystemTray.getSystemTray();
    try
    {
        systemTray.add(trayIcon);
    } catch (AWTException ex)
    {
        Logger.getLogger(mainframe.class.getName()).log(Level.SEVERE, null, ex);
    }

创建MouseAdapter并为任务栏图标添加mouseListener

Create MouseAdapter and add mouseListener for tray icon

MouseAdapter trayIconMouseAdapter = new MouseAdapter()
    {
      //  @Override
       public void mouseClicked(MouseEvent e) {
                trayIconMouseClicked(e);
       }
    };

   trayIcon.addMouseListener(trayIconMouseAdapter);

处理托盘图标上的鼠标单击事件.检查是否右键单击并显示弹出菜单

handle mouse click event on tray icon. Check whether it is a right click and show popupmenu

private void trayIconMouseClicked(java.awt.event.MouseEvent evt) {

    if(SwingUtilities.isRightMouseButton(evt))
    {
      popupMeunu.show(evt.getComponent(), evt.getX(), evt.getY());

    }
}

但是如果我将按钮悬挂到jframe并用 popupMeunu.show替换 popupMeunu.show(evt.getComponent(),evt.getX(),evt.getY()); (jButton1,evt.getX(),evt.getY()); 一切都会好的.

But if i drap a button to jframe and replace popupMeunu.show(evt.getComponent(), evt.getX(), evt.getY()); by popupMeunu.show(jButton1, evt.getX(), evt.getY()); everything will be OK.

我不知道为什么?请帮助我解决问题.

I don't know why?Pls help me to slove my problem.

推荐答案

不要添加自己的MouseListener.

Don't add your own MouseListener.

在...的构造函数中传递您的 popupMeunu (需要是 java.awt.PopupMenu ,而不是 javax.swing.JPopupMenu ).像这样的 TrayIcon :

Pass your popupMeunu (which needs to be a java.awt.PopupMenu, not javax.swing.JPopupMenu) in the constructor of TrayIcon like that:

TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup);

我从教程复制了此文件,并且效果很好.

I copied this from this tutorial and it worked fine.

这篇关于如何在Java中使用带有托盘图标的上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:16