2017-05-02 123 views
0

您好,我想將月份名稱轉換爲月份數字,我使用的是代碼形式,但看起來像幼稚。如何在Java中將月份名稱轉換爲月份數字使用JCombobox

我有12個月的JComboBox

 JCombobox month_sands = new JComboBox(); 

     month_sands.addItem("January"); 
     month_sands.addItem("February"); 
     month_sands.addItem("March"); 
     month_sands.addItem("April"); 
     month_sands.addItem("May"); 
     month_sands.addItem("June"); 
     month_sands.addItem("July"); 
     month_sands.addItem("August"); 
     month_sands.addItem("September"); 
     month_sands.addItem("October"); 
     month_sands.addItem("November"); 
     month_sands.addItem("December"); 

所以在這裏我想月份數字時,我選擇了每月

比如我寫的代碼月份轉換爲數字,

String month=null; 
if(month_sands.getSelectedItem().equals("January")) 
    { 
     month="01"; 
    } 
    if(month_sands.getSelectedItem().equals("February")) 
    { 
     month="02"; 
    } 
    if(month_sands.getSelectedItem().equals("March")) 
    { 
     month="03"; 
    } 
    if(month_sands.getSelectedItem().equals("April")) 
    { 
     month="04"; 
    } 
    if(month_sands.getSelectedItem().equals("May")) 
    { 
     month="05"; 
    } 
    if(month_sands.getSelectedItem().equals("June")) 
    { 
     month="06"; 
    } 
    if(month_sands.getSelectedItem().equals("July")) 
    { 
     month="07"; 
    } 
    if(month_sands.getSelectedItem().equals("August")) 
    { 
     month="08"; 
    } 
    if(month_sands.getSelectedItem().equals("September")) 
    { 
     month="09"; 
    } 
    if(month_sands.getSelectedItem().equals("October")) 
    { 
     month="10"; 
    } 
    if(month_sands.getSelectedItem().equals("November")) 
    { 
     month="11"; 
    } 
    if(month_sands.getSelectedItem().equals("December")) 
    { 
     month="12"; 
    } 

,但我並不滿足於這樣的代碼,有沒有其他辦法讓它短表

回答

3

您可以使用getSelectedIndex()代替getSelectedItem()並將1添加到它以獲取月份編號。

+0

是的:好多了 –

+0

這對我有用謝謝 –

0

我建議使用此代碼:

閱讀更多關於JComboboxgetSelectedIndex方法

String month = null; 

if(month_sands.getSelectedIndex() != -1){ 
    month_sands = "0"+(month_sands.getSelectedIndex() + 1); 
} 
0

你可以像下面這樣做的每一個對象,顯現在JComboBox中: 用於創建自定義對象像這樣的組合框

IdAndName idAndName= new IdAndName(month, id); 

然後,將所有值添加到它,將IdAndNames的列表設置爲mo組合框的刪除。

combobox.setModel(list); 

一旦你這樣做,你可以顯示「名稱」,如果你想獲得的ID,你可以這樣說:

combobox.getSelectedItem().getId; 

我使用這個模板的所有組合框

相關問題