ComboBox:getSelectedIndex()在“重新选择”时行为异常

时间:2018-10-06 03:44:47

标签: java swing jcombobox

我的组合框的标识符为cmbYear

项目是1800、1801、1802、1803,...,...,2017、2018。

然后我运行项目。当我在用户界面中选择1801时,getSelectedIndex()返回1(在控制台中打印),这是正确的。

在同一运行中,如果我再次选择1802,则getSelectedIndex()仍返回1。在随后的每个选择中,getSelectedIndex()返回1,即第一个选择的索引。

getSelectedIndex()是通过cmbYearActionPerformed(java.awt.event.ActionEvent evt)方法调用的。

请问我该如何解决这个问题?

下面是相关的行。

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package agecalcagain.UI;

import java.awt.event.ItemEvent;
import java.util.Calendar;
import javax.swing.JComboBox;

/**
 *
 * @author MuhammadRaselParvej
 */
public class AgeCalcAgain extends javax.swing.JFrame {

    private Integer[] yearList;
    private Integer[] dayList;
    private int selectedMonthIndex=0;
    private int selectedYearIndex=0;

    private void newMonthIndex(){
       selectedMonthIndex = cmbMonth.getSelectedIndex(); 
       System.out.println("Yes, new month :"+ String.valueOf(months[selectedMonthIndex]));
    }

    private void newYearIndex(){
        selectedYearIndex = cmbYear.getSelectedIndex();
        System.out.println("Yes, new year :"+ yearList[selectedYearIndex]);
    }

    int p=1;

    Calendar today = Calendar.getInstance();
    String months[] = new String[]{"January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"};
    String eras[] = new String[]{"BC", "AD"};

    /**
     * Creates new form AgeCalcAgain
     */
    private void updateYearList() {
        int n = today.get(Calendar.YEAR);
        n = n - 1800 + 1;
        yearList = new Integer[n];

        for (int i = 0; i < n; i++) {
            yearList[i] = 1800 + i;
        }
    }

    private void updateDayList() {
        System.out.println("In updateDayList **************** "+ p++);
        int n = yearList[selectedYearIndex];
        System.out.println("n "+n);
        n = n % 100 == 0 ? n / 100 : n;
        System.out.println("n "+n);
        int m;
        m = selectedMonthIndex;
        m++;
        System.out.println("m "+m);
        int numberOfDays = 28;
        if (m == 2 && n % 4 == 0) {
            numberOfDays++;
        } else if (m != 2) {
            numberOfDays += 2;
        }
        if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
            numberOfDays++;
        }
        dayList = new Integer[numberOfDays];
        for (int i = 0; i < numberOfDays; i++) {
            dayList[i] = i + 1;
        }
        System.out.println(numberOfDays);
    }

    private void createTempCmbMonth() {
        cmbMonth = new JComboBox<String>(months);
    }

    private void createTempCmbYear() {
        cmbYear = new JComboBox<>(yearList);
    }

    public AgeCalcAgain() {
        updateYearList();
        createTempCmbYear();
        createTempCmbMonth();
        updateDayList();
        myInitComponents();

        this.lbl01.setText("Today is " + today.get(Calendar.DATE) + " "
                + months[today.get(Calendar.MONTH)] + ", " + today.get(Calendar.YEAR) + " " + eras[today.get(Calendar.ERA)]);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lbl01 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cmbDay = new javax.swing.JComboBox<>();
        cmbYear = new javax.swing.JComboBox<>();
        cmbMonth = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(500, 500));
        setPreferredSize(new java.awt.Dimension(500, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lbl01.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        lbl01.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl01.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(), javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(), javax.swing.BorderFactory.createCompoundBorder()), javax.swing.BorderFactory.createCompoundBorder())));
        getContentPane().add(lbl01, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 30, 270, 20));

        jLabel1.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Enter Your Birthdate");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, 180, 20));

        jLabel2.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Birthday");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 200, 80, -1));

        jLabel3.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Birthyear");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 110, 80, 30));

        jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Birthmonth");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 150, 80, 30));

        cmbDay.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbDay.setModel(new javax.swing.DefaultComboBoxModel<>(dayList));
        cmbDay.setSelectedItem(1);
        cmbDay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbDayActionPerformed(evt);
            }
        });
        getContentPane().add(cmbDay, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 200, 120, 30));

        cmbYear.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbYear.setModel(new javax.swing.DefaultComboBoxModel<>(yearList));
        cmbYear.setSelectedItem(yearList[selectedYearIndex]);
        cmbYear.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbYearItemStateChanged(evt);
            }
        });
        cmbYear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbYearActionPerformed(evt);
            }
        });
        getContentPane().add(cmbYear, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 110, 120, 30));

        cmbMonth.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbMonth.setModel(new javax.swing.DefaultComboBoxModel<>(months));
        cmbMonth.setSelectedItem(months[selectedMonthIndex]);
        cmbMonth.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbMonthItemStateChanged(evt);
            }
        });
        cmbMonth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMonthActionPerformed(evt);
            }
        });
        cmbMonth.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                cmbMonthPropertyChange(evt);
            }
        });
        getContentPane().add(cmbMonth, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, 120, 30));

        pack();
    }// </editor-fold>                        

    private void myInitComponents() {

        lbl01 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cmbDay = new javax.swing.JComboBox<>();
        cmbYear = new javax.swing.JComboBox<>();
        cmbMonth = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(500, 500));
        setPreferredSize(new java.awt.Dimension(500, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lbl01.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        lbl01.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl01.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(), javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createCompoundBorder(), javax.swing.BorderFactory.createCompoundBorder()), javax.swing.BorderFactory.createCompoundBorder())));
        getContentPane().add(lbl01, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 30, 270, 20));

        jLabel1.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Enter Your Birthdate");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, 180, 20));

        jLabel2.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Birthday");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 200, 80, -1));

        jLabel3.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Birthyear");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 110, 80, 30));

        jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Birthmonth");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 150, 80, 30));



        cmbYear.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbYear.setModel(new javax.swing.DefaultComboBoxModel<>(yearList));
        cmbYear.setSelectedItem(yearList[selectedYearIndex]);
        cmbYear.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbYearItemStateChanged(evt);
            }
        });
        cmbYear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbYearActionPerformed(evt);
            }
        });
        getContentPane().add(cmbYear, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 110, 120, 30));

        cmbMonth.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbMonth.setModel(new javax.swing.DefaultComboBoxModel<>(months));
        cmbMonth.setSelectedItem(months[selectedMonthIndex]);
        cmbMonth.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbMonthItemStateChanged(evt);
            }
        });
        cmbMonth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMonthActionPerformed(evt);
            }
        });
        cmbMonth.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                cmbMonthPropertyChange(evt);
            }
        });
        getContentPane().add(cmbMonth, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, 120, 30));


        cmbDay.setFont(new java.awt.Font("Arial Narrow", 0, 20)); // NOI18N
        cmbDay.setModel(new javax.swing.DefaultComboBoxModel<>(dayList));
        cmbDay.setSelectedItem(1);
        cmbDay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbDayActionPerformed(evt);
            }
        });
        getContentPane().add(cmbDay, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 200, 120, 30));

        pack();
    }// </editor-fold>                        



    private void cmbYearActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        newYearIndex();
        updateDayList();
        myInitComponents();

    }                                       


    private void cmbMonthActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        newMonthIndex();
        updateDayList();
        myInitComponents();
    }                                        

    private void cmbDayActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void cmbMonthPropertyChange(java.beans.PropertyChangeEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void cmbMonthItemStateChanged(java.awt.event.ItemEvent evt) {                                          
               // TODO add your handling code here:
    }                                         

    private void cmbYearItemStateChanged(java.awt.event.ItemEvent evt) {                                         
        // TODO add your handling code here:

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AgeCalcAgain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AgeCalcAgain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AgeCalcAgain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AgeCalcAgain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AgeCalcAgain().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JComboBox<Integer> cmbDay;
    private javax.swing.JComboBox<String> cmbMonth;
    private javax.swing.JComboBox<Integer> cmbYear;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lbl01;
    // End of variables declaration                   
}   

1 个答案:

答案 0 :(得分:2)

不要在监听器中调用myInitComponents(),因为在此方法中,您将创建全新的GUI组件,并将它们全部设置为初始状态,这给您带来了大麻烦。而是编写将当前组件设置回其初始状态(或所需的任何状态)的代码。