I am trying to make a time picker using JSpinner and Java 8's time API. I want to make a time picker without date.
Before, I was using SimpleDateFormat, but that would return time with date when I print out the value of the JSpinner.
So how can I pass the value of a LocalTime object into the setValue method of a JSpinner?
Here is my current code:
JSpinner timeSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(timeEditor);
LocalTime newTime = LocalTime.of(11, 9);
timeSpinner.setValue(newTime);
timeSpinner.setBounds(126, 55, 56, 22);
contentPanel.add(timeSpinner);
Or am I taking the wrong approach to this?
This is my original code which works:
JSpinner timeSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(timeEditor);
SimpleDateFormat time = new SimpleDateFormat("HH:mm");
try {
timeSpinner.setValue(time.parseObject("10:00"));
} catch (ParseException timeError) {
timeError.printStackTrace();
}
timeSpinner.setBounds(126, 55, 56, 22);
contentPanel.add(timeSpinner);
Yes, method
getValue(), of classSpinnerDateModel, returns an instance ofjava.util.Date()but you can convert that into aLocalTimeas follows:As you can see, there are two ways to convert
java.util.DatetoLocalTime, depending on which JDK version you are using.The above code will print
theTimein formatHH:mm