簡體   English   中英

java.lang.ClassCastException: com.codename1.ui.Label cannot be cast to com.codename1.components.MultiButton

[英]java.lang.ClassCastException: com.codename1.ui.Label cannot be cast to com.codename1.components.MultiButton

我一直在做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);
    }

output 指出了這一行的錯誤:

MultiButton mb = (MultiButton)cmp;

我相信錯誤實際上是在前面的代碼中,而不是在您在這里提交的代碼中。 您在此處提供的代碼(從您還提供的鏈接中提取)假定f.getContentPane()僅包含MultiButton而沒有其他類型的Component

在您鏈接的示例中,創建者正在迭代組件,將每個組件轉換為MultiButton 為了使這個轉換成功,在循環的每次迭代中分配給cmpMultiButton實際上必須是一個 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 .

修復:要么確保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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM