铸造 JMenuItem

Casting JMenuItem

在我的 actionPerformed 方法中,我有以下两行代码,

JButton pressed =(JButton)e.getSource();
JMenuItem pressedSave = (JMenuItem)e.getSource();

为什么不允许这样做?我收到以下编译器错误

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JMenuItem

我需要能够获取 JButtonJMenuItem 的文本。我该怎么做?

错误很明显。您正在尝试将 Jbutton 分配给 JMenuItem

您在 第 2 行 上收到错误,这意味着 第 1 行 是完美无缺的,这也意味着 e.getSource()JButton,而不是 JMenuItem

您可以使用 instanceof 运算符来确定哪个组件触发了事件:

Object comp = e.getSource();

if(comp instanceof JButton) {
    // A JButton triggered the event
    JButton pressed =(JButton) comp;

    // Do something with your 'pressed' button
}
else if(comp instanceof JMenuItem) {
    // A JMenuItem triggered the event
    JMenuItem pressedSave = (JMenuItem) comp;

    // Do something with your 'pressedSave' menu item
}

您没有收到编译器错误。

"allowed",就是不行

如果不允许,编译器会报错。

但是您在这里得到的是一个 RuntimeException,因为您 有一个 一个 JButton,它根本无法转换为一个 JMenuItem。它们是不相关的类型——这两者之间的转换/转换应该是什么样子的?

可以做的是将类型 JButtonJMenuItem 转换为它们共同的超类型 AbstractButton.

JMenuItem 不是 JButton 的子类,但是您可以将两者都转换为 AbstractButton。这可能会起作用,具体取决于你想做什么