Problem getting the JPopupMenu from the Action it generates
I'm having a problem getting the JPopupMenu from an Action that is
generated by the JPopupMenu. The error is a ClassCastException and it
is saying that what is returned by ActionEvent.getSource() cannot be
cast to a JPopupMenu because it is a JPopupMenu$1. JPopupMenu$1 is an
anonymous class and shouldn't be returned by ActionEvent.getSource().
In the end, I'm trying to get to the component that was right clicked to
pop up the menu.
I'm stumped, any ideas?
Thanks,
C:\Users\Knute Johnson\com\knutejohnson\cookbook>java test
javax.swing.JPopupMenu$1[,1,3,97x21,invalid,alignmentX=0.0,alignmentY=0.0,border
=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@23b2ab4,flags=264,maximumSiz
e=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,
margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBor
der=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rollo
verSelectedIcon=,selectedIcon=,text=do something]
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
javax.swing
..JPopupMenu$1 cannot be cast to javax.swing.JPopupMenu
at test$someAction.actionPerformed(test.java:29)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown
Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown
Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at
javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown
Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame {
final JPopupMenu popupMenu;
public test() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
popupMenu = new JPopupMenu();
popupMenu.add(new someAction());
JTextField tf = new JTextField("textField");
tf.setComponentPopupMenu(popupMenu);
add(tf,BorderLayout.CENTER);
pack();
setVisible(true);
}
public class someAction extends AbstractAction {
public someAction() {
putValue(NAME,"do something");
}
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getSource());
System.out.println();
System.out.println((JPopupMenu)ae.getSource());
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new test();
}
});
}
}
--
Knute Johnson