2016-08-04 80 views
0

我有兩個組合框下面,的Java設計多個值的情況

enter image description here

每當我點擊done按鈕,我從組合框中的值,並將其存儲在一個對象像下面,

public class comboValues{ 
private String label1ComboString; 
private String label2ComboString; 

public String setLabel1Combo(String val){ 
this.label1ComboString = val; 
} 

public String setLabel2Combo(String val){ 
this.label2ComboString = val; 
} 

public void getLabel1Combo(){ 
return this.label1ComboString; 
} 

public void getLabel2Combo(){ 
return this.label2ComboString; 
} 
} 
在控制器類別I

 comboValues obj = new comboValues(); 
     obj.setLabel1Combo(label1ComboBox.getSelectionModel().getSelectedItem()); 
     obj.setLabel2Combo(label2ComboBox.getSelectionModel().getSelectedItem()); 

對於帶有兩個組合框的設計,代碼看起來很簡單。如果組合框的數量增加,我的疑問是什麼?用上面的方法代碼會有 很多行。什麼是設計來克服這個問題,我怎樣才能實現這種情況?

+2

使用某些數組,列表或地圖? – 2016-08-04 05:13:17

+1

你可以使用'Map' – sidgate

+2

我不認爲你想要一個設計模式,就像Factory Pattern或Singleton Pattern一樣。我認爲你需要一個數據結構,如Map或ArrayList,或者一個包裝數據結構並提供更多功能的類。 –

回答

-1

我可以從你的方法看到,你想添加更多的組合框,並針對它,你想在java中做更少的代碼來處理這些。

您可以選擇實施陣列列表收集並在其中存儲多個組合框。所以每次你不需要創建新的對象,它就會變成動態的。

希望它能清除你的疑惑。如果你還沒有清除請評論。

0

您可以有一個數組或組合框的ArrayList。這樣你可以引用任意數量的方框。你的班級會變成這樣的:

public class ComboValues { 
    private String[] comboStrings; 
    ... 
    public void setComboLabel(String label, int comboNum) { 
     comboStrings[comboNum] = label; 
    } 
    public void getComboLabel(int comboNum) { 
     return comboStrings[comboNum]; 
    } 
    public void getComboBoxCount() { 
     return comboStrings.length; 
    } 
} 

... 
String[] labels = ... 
for (int i = 0; i < obj.getComboBoxCount(); i++) { 
    obj.setComboLabel(labels[i], i); 
}