我正在使用 NetBeans 进行 Java 编程。我有一个奇怪的问题。在类 Mouse Listener 中,我执行面板的 getComponents 操作,它返回一个组件数组,我将这些组件放入一个数组 JButton (惠特转换)中(?),所以..
JButton[] b= (JButton[])Main.p1.getComponents();
IDE 不显示错误。 例如,我这样做:
b[0].setBackground(Color.yellow);
在输出中我看到一个错误。
但如果我这样做
JButton b= (JButton) Main.p1.getComponents()[0];
b.setBackground(...);
一切正常,但我不明白为什么。有人可以解释一下吗?
2015-01-18
谢谢大家的回答。 我想要获取面板的组件,不仅可以更改背景颜色,还可以更改坐标;我需要数组中的所有按钮同时进行比较。为什么我无法转换“按钮”中的“组件”?面板有一个指向 RAM 内存中按钮的指针。 Patryk Dobrowolski 谢谢你,我试试这个:(我使用 Button 类扩展 JButton)
Button[] button = new Button[Main.p1.getComponents().length];
for (int i = 0; i < Main.p1.getComponents().length; i++) {
button[i] = (Button) Main.p1.getComponents()[i];
}
但在输出中我看到这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JLabel cannot be cast to Button
为什么选择 JLabel?
Hovercraft Full Of Eels,谢谢你的回答,我可以创建一个数组并将所有Button的指针插入其中。但我说:JPannel 有一个数组,其中插入指针..我可以使用它。为什么不? 非常感谢你!
亚历山德罗·阿梅代伊
最佳答案
在第一种情况下,您对编译器撒了谎。通过声明
JButton[] b= (JButton[])Main.p1.getComponents();
您告诉编译器您知道这是一个 JButton
数组,而实际上它实际上是一个 Component
数组。因此,您不会遇到编译时错误,但会在运行时出现错误。
在另一种情况下,它可以工作,从那时起,您就告诉编译器您想要使用的 Component
是一个 JButton
,这是事实。
关于java - 转换组件[] -> JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000265/