如果我尝试更改值,我的 JSpinner 会跳转到 1970

My JSpinner jumps to 1970 if i try to change the value

就像我在标题中描述的那样,我的微调器显示了我的数据库中一年中的第几周,并且格式化的文本字段显示了给定一周的第一天。 到目前为止一切正常,但如果我尝试更改微调器的周数,日期会跳转到 1970 年。

这是我的 SpinnerModel:

spinner_KW.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.WEEK_OF_YEAR));

这是我从数据库和 DateEditor 设置值的代码:

public void setDateKWSpinner(Date kw){
    JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(spinner_KW, "w");
    spinner_KW.setEditor(timeEditor);        
    spinner_KW.setValue(kw); // will only show the current time
    setWeekfromto();
}

我真的希望我的问题不像我想象的那么愚蠢-.-

更新

作为请求,这里是一个显示问题的小 运行 代码:

package datespinner_test;

import java.util.Calendar;
import java.util.Date;
import javax.swing.JSpinner;

public class SpinnerJFrame extends javax.swing.JFrame {

    public SpinnerJFrame() {
        initComponents();
        setDateKWSpinner();
        setWeekfrom();
    }

    public void setDateKWSpinner(){
        JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(dateSpinner, "w");
        dateSpinner.setEditor(timeEditor);
        dateSpinner.setValue(new Date());
    }

    public void setWeekfrom(){
        Calendar cal = Calendar.getInstance();
        cal.setTime((Date) dateSpinner.getModel().getValue());
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        firstDayofWeek.setValue(cal.getTime());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        dateSpinner = new javax.swing.JSpinner();
        firstDayofWeek = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        dateSpinner.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.WEEK_OF_YEAR));
        dateSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                dateSpinnerStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(dateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(firstDayofWeek, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(190, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(firstDayofWeek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void dateSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {                                         
        setWeekfrom();
    }                                        

    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(SpinnerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SpinnerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SpinnerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SpinnerJFrame.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 SpinnerJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JSpinner dateSpinner;
    private javax.swing.JFormattedTextField firstDayofWeek;
    // End of variables declaration                   
}

编辑:满载鳗鱼的气垫船在评论中抢先一步。 更好的解决方案在


我想问题是从这一行开始的:

JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(dateSpinner, "w");

这将构建一个存储日期但仅显示年份日期的 DateEditor。当然,这会丢失信息,当尝试根据用户输入进行更新并从一周恢复到一整年时,引擎盖下使用的 SimpleDateParser 会填充缺失的信息作为纪元的开始,即 1970 年。

一个可能的解决方法是只读取从那个日期开始的星期,并用它来更新日期显示:

public void setWeekfrom(){
    Calendar cal = Calendar.getInstance();
    Calendar calWeekOnly = Calendar.getInstance();
    calWeekOnly.setTime((Date) dateSpinner.getModel().getValue());
    cal.set(Calendar.WEEK_OF_YEAR, calWeekOnly.get(Calendar.WEEK_OF_YEAR));
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    firstDayofWeek.setValue(cal.getTime());
}

但是,如果一周低于零(实际上甚至超过 2)或超过 52,这会导致奇怪的 "wrap around" 影响。