1

I'm in trouble with a problem of the Java JSpinner. If I do not modify the value which is displayed in the spinner everything works. But if I change the value (a date) using the arrows my program returns to me the date of 1th January 1970.

Here's the snippet of code:

package main;

import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class GUI {

JSpinner mySpinner;



public void createGUI(){
    JFrame frame=new JFrame();
    JPanel panel=new JPanel(new FlowLayout());

    panel.setSize(300,100);
    mySpinner=new JSpinner();
    mySpinner.setModel(new SpinnerDateModel(new Date(), null, null, Calendar.MINUTE));
    mySpinner.setEditor(new JSpinner.DateEditor(mySpinner, "HH:mm"));
    mySpinner.setBounds(0, 0, 71, 28);

    final JLabel myLabel=new JLabel();
    panel.add(myLabel);

    mySpinner.addChangeListener(new ChangeListener(){

        @Override
        public void stateChanged(ChangeEvent e) {
            System.out.println("JSpinner: "+mySpinner.getValue());

        }

    });


    frame.add(panel);
    panel.add(mySpinner);
    frame.setVisible(true);

}

}

This is the main:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    GUI myGUI=new GUI();
    myGUI.createGUI();
}

And this is what console prints:

JSpinner: Thu Jan 01 23:03:00 CET 1970
JSpinner: Thu Jan 01 22:03:00 CET 1970
Giacomo Bartoli
  • 730
  • 3
  • 9
  • 23
  • You've got a bug somewhere in your code, likely in code not shown us. I suggest that you consider creating and posting a [minimal example program](http://stackoverflow.com/help/mcve). Also some unrelated recommendations: you will want to avoid use of null layout as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Also I would not name my JSpinner formattedTextField as that would be confusing. – Hovercraft Full Of Eels Apr 13 '14 at 16:48
  • Actually I was wrong -- your description is enough to show the problem. I've posted code, a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve), that I think reproduces it. – Hovercraft Full Of Eels Apr 13 '14 at 16:57
  • I rewrite the code as you suggest. Now it's more simple. – Giacomo Bartoli Apr 13 '14 at 17:10
  • Check MadProgrammer's answer [here](http://stackoverflow.com/a/14455065/522444) to a similar question. – Hovercraft Full Of Eels Apr 13 '14 at 17:10

1 Answers1

-1

You need to set todays date to DateEditor. Try following snippet.

Date today = new Date();
JSpinner s = new JSpinner(new SpinnerDateModel(today, null, null,
    Calendar.MINUTE));
JSpinner.DateEditor de = new JSpinner.DateEditor(s, "HH:mm");
s.setEditor(de);

Hope it helps.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Swapnil
  • 13
  • 4