I'm using a jSpinner to set the time with format "HH:MM" and it works fine.
My problem is I want to set my jSpinner to "00:00" when the window is activated, and once jSpinner is clicked I want the value to be changed to the "HH:MM" format. And I can't do it myself, the jSpinner value doesn't change it is still "00:00". Please help me. Thank you in advance.
Assuming that your are using a SpinnerDateModel
, then the value that the JSpinner
is managing is java.util.Date
. You need to create a Date
instance which has it's hour/minute fields set to midnight
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
Date date = cal.getTime();
spinner.setValue(date);
To get the format the value from the JSpinner
, you can use a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String value = sdf.format(spinner.getValue());
but how can I set it with "00:00" when the window is activated
Without more information, I'd suggest using a WindowListener
of some kind, assuming that you're not creating the window each time.
Have a look at How to Write a Focus Listener and How to Write Window Listeners
And changed the value once clicked?
That's a little unclear, but you should just get the value from the JSpinner
at the time you need to know what it is and format based on your needs. The JSpinner
should be taking care of formatting the value automatically (based on your settings) when the values is updated.
Having said that, I did need to make the "start" (or lowest value) null
when I set up the model, which seemed to allow the spinner to update the time value
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
Date startTime = cal.getTime();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
Date endTime = cal.getTime();
System.out.println(startTime);
System.out.println(endTime);
// The Calendar field seems to get ignored and overriden
// by the UI delegate based on what part of the field
// the cursor is current on (hour or minute)
SpinnerDateModel model = new SpinnerDateModel(startTime, null, endTime, Calendar.MINUTE);
JSpinner spinner = new JSpinner(model);
spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));
spinner.setValue(startTime);
来源:https://stackoverflow.com/questions/30093154/how-to-set-jspinner-default-value