简体   繁体   中英

How to get Date from my JSpinner?

this is the code of the Spinner

Hini = new javax.swing.JSpinner();
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.MINUTE);
JSpinner Hini = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(Hini, "hh:mm a");
de.getTextField().setEditable( true );
Hini.setEditor(de);

And this is how i want it to get the values, but it always shows "00:00"

    `SimpleDateFormat formater = new SimpleDateFormat("HH/mm");
     String spinnerValue = formater.format(Hini.getValue());
     System.out.println(spinnerValue);`

I also tried this but it always showed the actual time, not the one I picked

Hini = new JSpinner(sm);
de = new JSpinner.DateEditor(Hini, "hh:mm a");
de.getTextField().setEditable( false );
Hini.setEditor(de);
System.out.println("Spinner:      "+de.getFormat().format(Hini.getValue()));

You seem to be creating two instance of the JSpinner

// Instance(?) field here...
Hini = new javax.swing.JSpinner();
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.MINUTE);
// Local field here
JSpinner Hini = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(Hini, "hh:mm a");
de.getTextField().setEditable( true );
Hini.setEditor(de);

So I can only guess that the local field is what is getting added to the UI and the instance field is been ignored, meaning that whatever the user enters into the field isn't been set to the instance field.

Drop the creation of the second field and replace it with Hini.setModel(sm);

Instead of formatting the value directly from the JSpinner , you should simply get a reference to the Date value and only format when you really need to. This provides you with a more flexible solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM