如何使用 JCombobox 将 java 中的月份名称转换为月份编号

How to Convert Month Name to Month Number in java Using JCombobox

大家好,我想将月份名称转换为月份编号,我使用的是代码形式,但它看起来很幼稚。

我在 JCombobox 中有 12 个月

        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");

所以我想在 select 月份

时获取月份编号

示例我编写了将月份转换为数字的代码,

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";
    }

但我对这段代码不满意,有没有其他方法可以使它更短

您可以使用 getSelectedIndex() 代替 getSelectedItem() 并向其添加 1 以获得月份数。

我建议使用此代码:

详细了解 JComboboxgetSelectedIndex 方法

String month = null;

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

您可以对 JComboBox 中显示的每个对象都这样做: 像这样为组合框创建自定义对象

IdAndName idAndName= new IdAndName(month, id);

然后在将 IdAndNames 列表设置为组合框的模型时向其添加所有值。

combobox.setModel(list);

完成后,你可以显示'name',如果你想获取id,你可以这样获取:

combobox.getSelectedItem().getId;

我将此模板用于所有组合框