且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JSpinner给出了旧的价值观

更新时间:2023-02-27 09:24:07

Java swing使用MVC模式,因此它在JSpinner中是相同的。如果查看JSpinner源代码,您会发现getValue()方法实际上是调用getModel()。getValue(),因此它调用模型的getValue。你使用的模型是SpinnerDateModel,它的值是Date Object,当你打印Date对象时,它会显示默认格式,如Thu Jan 01 11:18:00 IST 1970,如果你想获得像11:18之类的东西,你需要自己格式化。像

Java swing use a MVC pattern, so it is the same in JSpinner. If you look into JSpinner source code, you will find that the getValue() method is actually call getModel().getValue(), so it is calling the model's getValue. and the model you use is SpinnerDateModel, and the value of it will be Date Object,when you print the Date object, it will display the default format like "Thu Jan 01 11:18:00 IST 1970", if your want to get something like "11:18", you will need to format it yourself.like

 SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
 System.out.println(sdf.format(spinner.getValue()) );

您可能想知道为什么tf.getText()只获取旧值,因为在ChangeEvent之后spinner发生时,tf上会发生一个PropertyChangeEvent,会为它设置新值。当然,您可以像tf.addPropertyChangeListener一样收听tf。但我建议使用上面的解决方案。

You may wonder why tf.getText() only get the old value, because after the ChangeEvent on the spinner occurs, a PropertyChangeEvent on the tf will occurs,will set the new value to it. Of course, you can listen to tf like tf.addPropertyChangeListener. but i will suggest use the solution above.