2015-05-17 57 views
-1

尋找一種方法來改變輸出到組合框的數據,通過選擇單選按鈕,但是數據被從文本文件中拉出並保存到一個數組中,然後傳回到JCOMBO數組列表。對不起,如果問題是一個很大的含糊不清,我不知道該怎麼說。但文件由兩個不同的TXT文件分開,我可以輕鬆地從中返回數據。單選按鈕改變JCombo數據

ArrayList<String> stations = Reader("Default.txt"); 

    JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()])); 
    JRadioButton belgrave = new JRadioButton("Belgrave Line"); 
    belgrave.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
      cb.removeAllItems(); 
      stations.clear(); 
      ArrayList<String> stations = Reader("Belgrave.txt"); 
      JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()])); 
     } 
    }); 
    JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line"); 
    glenwaverly.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e){ 
      cb.removeAllItems(); 
      stations.clear(); 
      ArrayList<String> stations = Reader("Glenwaverly.txt"); 
      JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()])); 
     } 
    }); 
    ButtonGroup bG = new ButtonGroup(); 
    JButton apply = new JButton("Touch on ?"); 
    JButton cancel = new JButton("Cancel"); 
+1

所附例如不包含任何努力來處理單選按鈕改變combbobox的內容的邏輯。 –

+0

是啊,因爲我不知道如何通過單選按鈕來改變 –

+0

*「抱歉,如果問題是一個大模糊的」* ..什麼'問題'?就我所知,你沒有提出任何問題,只要給出一個需求和一個(不可編譯的)你的工作模板,以供其他人完成。 –

回答

1

就像你加入到applycancel按鈕,您將需要一個動作監聽器適用於單選按鈕以及動作監聽。

然後做類似下面的事情。

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {            
    //suppose this is your file input, that you will have to read 
    String[] test = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; 
    //your combobox name supposed it is combo 
    //remove all the previous items 
    combo.removeAllItems(); 
    //add all the items of the array(there is no addAll method) 
    for(int i=0; i<test.length; i++) 
     combo.addItem(test[i]); 
} 

希望它有幫助。

請注意,從TXT文件讀取數據並將其解析爲數組與txt的結構有關。看看here如何逐行閱讀一個TXT文件。


編輯

在你的聽衆,你要創建一個新的本地組合框。不過cb裏面的聽衆和聽衆之外的cb是不一樣的,它只是一個變量,創建的&只能在方法內部知道。您需要直接調用cb而不創建新對象。

替換此JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]))

String[] items = stations.toArray(new String[stations.size()]; 
for(int i=0; i<items.length; i++) 
     cb.addItem(items[i]); 
+0

嘿,謝謝我試着用一個正常的動作監聽器來做這件事。但它似乎只是清除了JCOMBO框而沒有插入任何數據。我會更新代碼,告訴你有什麼 –

+0

@VaughanD看到更新的答案。 – nmargaritis