0

我想让我的应用程序在任务栏上最小化,并在双击trayIcon时恢复。我也有一个弹出菜单,其中有一个项目可以在点击时恢复窗口。ActionListener和MouseListener冲突

trayIcon = new TrayIcon(image, "Anything", popup); 
    trayIcon.addActionListener(actionListener); 
    trayIcon.addMouseListener(mouseListener); 
    sysTray.add(trayIcon); 

这里是actionListenermouseListener的代码:

​​

弹出菜单的Restore选项工作正常,但是当我在系统托盘我的trayIcon双击得到Null Pointer Exception在线if(e.getActionCommand().equals("Restore"))

我该如何消除这种情况,如果可能的话,将两个听众合并为一个?

+0

为什么你甚至需要鼠标监听器或检查动作命令?仅在双击/键盘选择时调用动作侦听器 – Ordous

+0

我正在检查ActionEvent,因为我有多个菜单项,并且需要区分它们,但我省略了其余部分的代码。当我选择菜单中的一个项目时,ActionListener也会被调用。然而,你对MouseListener是正确的,实际上我正在寻找一种将MouseListener实现到ActionListener中的方法。 –

+0

我个人不喜欢为不同的动作使用单个ActionListener的做法。其中一个原因是它会在所有事件中强制使用相同的信息,即使它不适用。这是其中一种情况 - trayIcon根本不会填充“ActionCommand”。我实现的解决方案是使用一个“RestoreListener”,它只是在没有任何检查的情况下恢复该帧,并将该监听器放在还原菜单项和仅托盘图标**上**。 – Ordous

回答

1

N.B.这个答案是从注释中的OP对话取得,以及一些解决方案从OP

TrayIcon来到不填充ActionCommand场触发事件时,因此代码死亡与NPE。

由于托盘图标只要求其ActionListener只有当双次点击或以相似的动作(通过键盘),您可以创建一个RestoreListener不检查条件可言,并且只与托盘图标和使用“还原”菜单项。

private ActionListener restoreListener = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     // Do the actual restoration 
    } 
}; 

而实际上它添加到项目...

trayIcon = new TrayIcon(image, "Anything", popup); 
trayIcon.addActionListener(restoreListener); 

MenuItem restoreMenuItem = new MenuItem(...); 
restoreMenuItem.addActionListener(restoreListener); 

这似乎从MouseListener表现略有不同,它并没有把最上面的窗口,这可以通过调用toTop()予以纠正在上面。