How to get Date from my JSpinner?

落花浮王杯 提交于 2019-12-11 12:06:41

问题


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

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

回答1:


You seem to be creating two instance of the 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);

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.

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

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



来源:https://stackoverflow.com/questions/28162285/how-to-get-date-from-my-jspinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!