我有一个代表一天的JTextField,例如“星期日”,当我左键单击它时,它会更改背景颜色,当我右键单击它时,会出现一个弹出菜单,单击菜单项后,例如“1st of month”,它获取值,关闭菜单然后更改bgcolor,我的代码如下所示:
JTextField dayHeading=new JTextField("Su");
......
final JPopupMenu Pmenu;
JMenuItem menuItem;
Pmenu=new JPopupMenu();
menuItem=new JMenuItem("1st of month");
Pmenu.add(menuItem);
menuItem=new JMenuItem("2nd of month");
Pmenu.add(menuItem);
......
menuItem.addMouseListener(new MouseAdapter()
{
public void mouseReleased(final MouseEvent e)
{
System.out.println(((JMenuItem)e.getComponent()).getText());
onHeadingClicked(e); // Error : java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JTextField
// How to get the orininal JTextField event that started this pop up menu, so I can pass it onto onHeadingClicked() ?
}
});
......
dayHeading.setEditable(false);
dayHeading.setFocusable(false);
dayHeading.addMouseListener(new MouseAdapter()
{
public void mouseReleased(final MouseEvent evt)
{
if (SwingUtilities.isLeftMouseButton(evt)) onHeadingClicked(evt);
else if (SwingUtilities.isRightMouseButton(evt)) Pmenu.show(evt.getComponent(),evt.getX(),evt.getY());
}
});
......
void onHeadingClicked(final java.awt.event.MouseEvent evt)
{
final javax.swing.JTextField fld=(javax.swing.JTextField) evt.getSource();
...
}
我的问题是:在 menuItem.addMouseListener 部分,如何获取启动此弹出菜单的原始 JTextField 事件,以便我可以将其传递给 onHeadingClicked() ?