如何从我的JSpinner获取日期? [英] How to get Date from my JSpinner?

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

问题描述

这是Spinner的代码

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

这是我想要得到的值,但它总是显示00:00

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


推荐答案

您似乎正在创建两个 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);

所以我只能猜测本地字段是添加到UI和实例字段被忽略,这意味着用户输入的任何内容都不会被设置为实例字段。

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.

删除第二个字段的创建,并将其替换为 Hini.setModel(sm);

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

而不是直接从 JSpinner ,你应该直接得到 Date 值的引用,只有当你真的需要时才能格式化。这为您提供了更灵活的解决方案

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

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

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