如何从字符串设置 JSpinner 的值? [英] How to set value of JSpinner from string?

查看:24
本文介绍了如何从字符串设置 JSpinner 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 JSpinner 设置一个时间值,然后将其作为 varchar 更新到我的数据库中,例如中午 12:00:00.但是,在另一种形式中,我想检索添加到我的数据库中的时间到更新表单中的 JSpinner 中.更新表单供用户更新他们之前选择的时间(例如,如上所述的 12:00:00 AM).现在默认时间值是当前时间.我尝试使用 .setValue() 方法,但它是一个非法值,因为我检索的时间是一个字符串.这是我的代码,使事情更清楚:

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());

.getVolDutyShift() 方法返回一个字符串(字符串格式的 12:00:00 AM)a 是我的对象,它调用 .getVolDutyShift() 方法.我应该如何解析这个 a.getVolDutyShift() 以便 JSpinner 将时间加载为我的数据库中的时间(12:00:00 AM)?

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)?

推荐答案

试试这个.它会将您的时间字符串转换为 java.sql.Time.

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 );

但是您应该始终将日期和时间保存在数据库中的原始数据类型中,而不是保存为 varchar

But you should always save date and time in their original data types in database and not as varchar

这篇关于如何从字符串设置 JSpinner 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆