2

Like i discribed in the title, my Spinner shows the week of year from my DB and a formated text field shows the first day of this given week. Everything works fine to this point, but if i try to change the Week of the Spinner the Date jumps to 1970.

This is my SpinnerModel:

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

And here is the Code where I set the value from the DB and the 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();
}

I realy hope my Problem isn't as dumb as I think it is -.-

UPDATE

As requestet here is a smal running code that shows the Problem:

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                   
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Margu
  • 175
  • 3
  • 14
  • If you don't get help soon, consider creating and posting an [sscce](http://sscce.org) or a [minimal example program/mcve](http://stackoverflow.com/help/mcve) where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem. – Hovercraft Full Of Eels Mar 29 '15 at 16:46
  • 1
    Looks like your question is similar to this one, [JSpinner.DateEditor must include year even though start and end is the same year](http://stackoverflow.com/questions/3875215/jspinner-dateeditor-must-include-year-even-though-start-and-end-is-the-same-year). It looks like the model gets its date value by parsing the String displayed in your JSpinner's editor. If all you have is a week number, then you get thre result from parsing that single number. – Hovercraft Full Of Eels Mar 29 '15 at 18:39
  • Note your minimal code can be shortened further. This small program demonstrates your problem: [pastebin](http://pastebin.com/00HFBTSA). – Hovercraft Full Of Eels Mar 29 '15 at 18:44
  • Thanks @Hovercraft Full Of Eels I didn't think about it that way. Knew it was some stupid mistake somewhere ;) – Margu Mar 29 '15 at 20:10

1 Answers1

1

Edit: Hovercraft Full Of Eels beat me to it in the comments. Better solution at https://stackoverflow.com/a/3894581/2040545


I guess the problem start on this line:

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

this builds a DateEditor that stored a date, but shows only the date of the year. Of course this looses information, and when trying to update from user input and get back from the week to a full year, the SimpleDateParser used under the hood fills in the missing information as the start of the epoch, i.e. 1970.

A possible workaround is to only read the week from that date and use this to update the date display:

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());
}

This causes odd "wrap around" effects if the week goes below zero (actually even beyound 2) or beyond 52, however.

Community
  • 1
  • 1
Clemens Klein-Robbenhaar
  • 3,457
  • 1
  • 18
  • 27