[英]java.lang.ClassCastException: com.codename1.ui.Label cannot be cast to com.codename1.components.MultiButton
i have been doing the SearchToolBar CodeNameOne API and ran into CLassCastException我一直在做SearchToolBar CodeNameOne API并遇到了 CLassCastException
for(Component cmp : f.getContentPane()) {
MultiButton mb = (MultiButton)cmp;
String line1 = mb.getTextLine1();
String line2 = mb.getTextLine2();
boolean show = line1 != null && line1.toLowerCase().indexOf(text) > -1 ||
line2 != null && line2.toLowerCase().indexOf(text) > -1;
mb.setHidden(!show);
mb.setVisible(show);
}
the output pointed the error on this line: output 指出了这一行的错误:
MultiButton mb = (MultiButton)cmp; MultiButton mb = (MultiButton)cmp;
I believe the error is actually in the preceding code and not in the code you have submitted here.我相信错误实际上是在前面的代码中,而不是在您在这里提交的代码中。 The code you have provided here (pulled from the link you also provided) assumes that
f.getContentPane()
only contains MultiButton
and no other type of Component
.您在此处提供的代码(从您还提供的链接中提取)假定
f.getContentPane()
仅包含MultiButton
而没有其他类型的Component
。
In the example you have linked, the creator is iterating through components, casting each one to a MultiButton
.在您链接的示例中,创建者正在迭代组件,将每个组件转换为
MultiButton
。 In order for this cast to succeed, the object that is assigned to cmp
in each iteration of the loop has to actually be a MultiButton
.为了使这个转换成功,在循环的每次迭代中分配给
cmp
的MultiButton
实际上必须是一个 MultiButton 。
In your code, while iterating in your for-loop, at one point cmp is assigned a value of type com.codename1.ui.Label
, this type is not a MultiButton
so the cast fails and throws the runtime exception java.lang.ClassCastException
. In your code, while iterating in your for-loop, at one point cmp is assigned a value of type
com.codename1.ui.Label
, this type is not a MultiButton
so the cast fails and throws the runtime exception java.lang.ClassCastException
.
To fix: either ensure that the ContentPane
only contains MultiButton
s or add a check inside your for loop to skip an iteration if the component isn't a MultiButton
like follows:修复:要么确保
ContentPane
仅包含MultiButton
,要么在你的 for 循环中添加一个检查以跳过迭代,如果组件不是MultiButton
如下所示:
for(Component cmp : f.getContentPane()) {
if(cmp instanceof MultiButton) {
// your original for-loop body here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.