问题
I currently am using a JSpinner to set a time value which is then updated to my database as a varchar e.g. 12:00:00 AM. However in another form I would like to retrieve this time that was added into my database into the JSpinner in my update form. The update form is for the user to update the time that they have selected before (e.g. 12:00:00 AM like stated above). Right now the default time value is the current time. I tried to use the .setValue() method but it is an illegal value as my retrieved time is a String. Here is my code to make things clearer:
shiftTime = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor de_shiftTime = new JSpinner.DateEditor(shiftTime,
"hh:mm:ss a");
shiftTime.setEditor(de_shiftTime);
shiftTime.setSize(108, 22);
shiftTime.setLocation(436, 478);
add(shiftTime);
shiftTime.setValue(a.getVolDutyShift());
The .getVolDutyShift() method returns a string (12:00:00 AM in string format) a is my object which calls the .getVolDutyShift() method. How should I parse this a.getVolDutyShift() so the JSpinner will load the time as the time in my database (12:00:00 AM)?
回答1:
Try this out. It will convert your time in string to java.sql.Time.
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss a");
java.util.Date d =(java.util.Date)format.parse(a.getVolDutyShift());
java.sql.Time time = new java.sql.Time(d.getTime());
shiftTime.setValue(time );
But you should always save date and time in their original data types in database and not as varchar
回答2:
I always had problems with parsing. I found another way, that solves your problem without parsing...
JSpinner.DateEditor de = new JSpinner.DateEditor(shiftTime, a.getVolDutyShift());
jSpinner1.setEditor(de);
来源:https://stackoverflow.com/questions/25105375/how-to-set-value-of-jspinner-from-string