JDK-6530871 : ClassCastException with JPopupMenu attached to TrayIcon
  • Type: Bug
  • Component: client-libs
  • Sub-Component: javax.swing
  • Affected Version: 6,7
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic,windows_xp
  • CPU: generic,x86
  • Submitted: 2007-03-05
  • Updated: 2011-01-19
  • Resolved: 2007-09-05
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 7
7Resolved
Related Reports
Duplicate :  
Duplicate :  
Relates :  
Relates :  
Description
Run the testcase below,
you'll see the messageBox and the green trayicon appear

Click on the green trayIcon ->
ava.lang.ClassCastException: java.awt.TrayIcon cannot be cast to java.awt.Component
	at javax.swing.plaf.basic.BasicPopupMenuUI$MouseGrabber.eventDispatched(BasicPopupMenuUI.java:810)
	at java.awt.Toolkit$SelectiveAWTEventListener.eventDispatched(Toolkit.java:2376)
etc...

comes up

===Test case===

OS: Windows XP
JDK 6,7 

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class bug {
    public static void main(String[] args) throws Exception {
        SystemTray tray = SystemTray.getSystemTray();
        TrayIcon ti = new TrayIcon(getImage(), "Hello");
        tray.add(ti);
        
        final JPopupMenu popup = new JPopupMenu("Menu");
        popup.add(new JMenuItem("Item"));
        
        ti.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                popup.setLocation(e.getX(), e.getY());
                popup.setVisible(true);
            }
        });
        
        JOptionPane.showMessageDialog(null, "message");
    }

    static Image getImage() {
        BufferedImage im = new BufferedImage(32, 35, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = (Graphics2D) im.getGraphics();
        g2.setColor(Color.GREEN);
        g2.fillRect(0, 0, im.getWidth(), im.getHeight());
        g2.dispose();
        return im;
    }
}

Comments
SUGGESTED FIX add if (!(ev.getSource() instanceof Component)) { return; } to the BasicPopupMenuUI.MouseGrabber.eventDispatched or rewrite the Swing support for trayIcon see 6285881
05-03-2007

EVALUATION The problematic casting happens in the BasicPopupMenu.MouseGrabber.eventDispatched() the mouseEvents comes from the trayIcon instance, so (Component)ev.getSource(); fails with the ClassCastException
05-03-2007