我试图使我的应用程序在任务栏上最小化并在双击trayIcon
时恢复。我还有一个弹出菜单,其中有一个项目可以在单击时恢复窗口。
trayIcon = new TrayIcon(image, "Anything", popup);
trayIcon.addActionListener(actionListener);
trayIcon.addMouseListener(mouseListener);
sysTray.add(trayIcon);
这是 actionListener
和 mouseListener
的代码:
private ActionListener actionListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Restore"))
{ // RIGHT CLICK -> RESTORE
// Do something
}
}
};
private MouseListener mouseListener = new MouseListener()
{
@Override
public void mouseClicked(MouseEvent e)
{
if (javax.swing.SwingUtilities.isLeftMouseButton(e) && e.getClickCount()>1)
{ // DOUBLE LEFT MOUSE CLICK
// Do something
}
}
// Rest of the code
}
弹出菜单的Restore
选项工作正常,但是当我双击系统托盘上的trayIcon
时,我得到一个空指针异常
位于 if(e.getActionCommand().equals("Restore"))
如何消除这种情况,如果可能的话,将两个监听器合并为一个?
最佳答案
注意这个答案是根据评论中与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()
来解决就在上面。
关于java - ActionListener 和 MouseListener 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24579087/