2012-04-19 14 views
0

我正在開發我的第一個(非常基本的)Java應用程序。儘管保存用戶信息,但遇到麻煩;具體而言,將來自文本字段的用戶輸入附加到JComboBox選擇。我該怎麼做呢?截至目前,我有:如何保存用戶輸入和JComboBox選擇?

String comps[] = {Computer 1, Computer 2, Computer 3}; //array for JComboBox 
jcbb = new JComboBox<String>(comps); //create JComboBox 

if (ae.getActionCommand().equals("Save")) { //user hits the Save button 

     StringBuilder sb = new StringBuilder(); //string to hold data 
     sb.append((String) macTF.getText()); //get data from textfield 
     sb.append(" "); 
     sb.append((String) jcbb.getSelectedItem()); //get JComboBox item 
     sb.append(" "); 
     //***what to do with the held data?*** 
    } 

我知道我錯過了很多,但只是在正確的方向微調將有所幫助。我一直在搜索書籍和網絡,發現了很多不同的答案,但我無法應用它們。我是否將StringBuilder輸出到文本文件並加載?或者用兩組數據構建一個數組?或者完全不同的東西?

感謝您的任何幫助。

回答

0

可以使用addItem方法(doc):

if (ae.getActionCommand().equals("Save")) { //user hits the Save button 
    String toAdd = (String) macTF.getText(); //get data from textfield 
    jcbb.addItem(toAdd); //add String to the combo box 
} 

另外,你會在這裏有一個問題:

String comps[] = {Computer 1, Computer 2, Computer 3}; //array for JComboBox 
jcbb = new JComboBox<String>(comps); //create JComboBox 

這應該是:

String comps[] = {"Computer 1", "Computer 2", "Computer 3"}; //array for JComboBox 
jcbb = new JComboBox(comps); //create JComboBox 
+0

謝謝talnicolas的快速反應!原諒我的無知,但addItem會將文本字段數據添加爲新的組合框選擇,還是將文本字段數據分配給現有的組合框選擇? – Sett 2012-04-19 20:50:45

+0

@Sett你是什麼意思*組合框選擇*? – talnicolas 2012-04-19 23:05:48

0

所以一個可能的解決方案如下,但缺點是由於添加/刪除元素和選擇的變化,它會產生大量事件。然而,就是你正在尋找

public <E> void replaceComboBoxItem(JComboBox<E> combo, E itemToReplace, E replacement){ 
    boolean selected = combo.getSelectedItem() == itemToReplace; 
    combo.insertItemAt(replacement, indexOf(combo, itemToReplace)); 
    combo.removeItem(itemToReplace); 
    if (selected){ 
     combo.setSelectedItem(itemToReplace); 
    } 
} 
private <E> int indexOf(JComboBox<E> combo, E item){ 
    for(int i =0; i < combo.getItemCount(); i++){ 
    if (combo.getItemAt(i).equals(item)){ 
     return i; 
    } 
    } 
    return -1; 
} 

的行爲,那麼你可以使用

replaceComboBoxItem(jcbb, jcbb.getSelectedItem(), sb.toString()); 

注:代碼只是在這裏打字,可能含有少量語法錯誤