2011-11-30 84 views
3

我有一個ArrayList<JCheckBox>,我想轉換爲ArrayList<String>我有一個ArrayList <JCheckBox>,我想轉換到一個ArrayList <String>

首先我不喜歡這個。我從文件中獲得所有標題,並將它們放入新的ArrayList中。後綴我創建了一個新的JCheckBox數組,其中包含StringArray中的所有字符串。

ArrayList<String> titler = new ArrayList<String>(); 
titler.addAll(FileToArray.getName()); 

ArrayList<JCheckBox> filmListe = new ArrayList<JCheckBox>(); 
for(String titel:titler){ 
    filmListe.add(new JCheckBox(titel)); 
} 
for(JCheckBox checkbox:filmListe){ 
    CenterCenter.add(checkbox); 
} 

這就是我要做的:首先,我做一個新的ArrayList(仍在對JCheckBox格式),包含全部選定的複選框。後綴我想以String格式添加到新的ArrayList中。

主要問題是斜體(帶**):

ArrayList<JCheckBox> selectedBoxes = new ArrayList<JCheckBox>(); 

for(JCheckBox checkbox: filmListe){ 
    if (checkbox.isSelected()){ 
     selectedBoxes.add(checkbox); 
    } 

ArrayList<String> titlesArr = new ArrayList<String>(); 
for(JCheckBox titel:selectedBoxes){ 
    *titlesArr.add(titel);* 
} 

大量的代碼和文本的一個小問題!但我真的很感謝你的幫助! :)

+1

我不確定我是否理解你想要實現的目標。 。 – mre

回答

1

假設複選框的標籤與您最初在標題列表中的標籤完全相同,只需使用複選框的getText方法(即獲取String標籤)即可。你不需要單獨列出被選中的複選框 - 只需在第一個循環內放置一個if塊即可:

ArrayList<String> titlesArr = new ArrayList<String>(filmListe.size()); 

    for (JCheckBox checkbox : filmListe) { 
     if (checkbox.isSelected()) { 
      titlesArr.add(checkbox.getText()); 
     } 
    } 
+0

非常感謝!我一直主演這個節目太久了。 :) – Strammefar

4

您不能將JCheckBox添加到List<String>,類型JCheckBoxString是不相容的。

我想你想的複選框的文本添加到您的列表,所以你必須手動檢索它,使用:

titlesArr.add(titel.getText()); 
0

試試這個:

ArrayList<String> titlesArr = new ArrayList<String>(); 
for(JCheckBox checkbox: filmListe) 
    if (checkbox.isSelected()) 
     titlesArr.add(checkbox.getText()); 

現在titlesArr包含你想要什麼。

+0

以這種方式在一個對象上使用'toString'是一個非常糟糕的想法,因爲你依賴於它的實現,通常只能用於調試。在你的情況下,在'JCheckBox'上調用'toString'會導致一個可怕的輸出,比如「javax.swing.JCheckBox [,0,0,0x0,invalid,alignmentX = 0.0,alignmentY = 0 ......」 – BoffinbraiN

+0

固定。提醒那些建設性的意見,*在* downvoting之前* –

+1

我這樣做搶先,但我總是可以un-downvote。 ;) – BoffinbraiN

相關問題