how to set jSpinner default value?

本秂侑毒 提交于 2019-12-04 19:07:22

Assuming that your are using a SpinnerDateModel, then the value that the JSpinner is managing is java.util.Date. You need to create a Date instance which has it's hour/minute fields set to midnight

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);

Date date = cal.getTime();
spinner.setValue(date);

To get the format the value from the JSpinner, you can use a SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String value = sdf.format(spinner.getValue());

but how can I set it with "00:00" when the window is activated

Without more information, I'd suggest using a WindowListener of some kind, assuming that you're not creating the window each time.

Have a look at How to Write a Focus Listener and How to Write Window Listeners

And changed the value once clicked?

That's a little unclear, but you should just get the value from the JSpinner at the time you need to know what it is and format based on your needs. The JSpinner should be taking care of formatting the value automatically (based on your settings) when the values is updated.

Having said that, I did need to make the "start" (or lowest value) null when I set up the model, which seemed to allow the spinner to update the time value

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);

Date startTime = cal.getTime();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
Date endTime = cal.getTime();

System.out.println(startTime);
System.out.println(endTime);

// The Calendar field seems to get ignored and overriden 
// by the UI delegate based on what part of the field
// the cursor is current on (hour or minute)
SpinnerDateModel model = new SpinnerDateModel(startTime, null, endTime, Calendar.MINUTE);
JSpinner spinner = new JSpinner(model);
spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));

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