JAVA中jspinner设置选中内容,如何设置jSpinner的默认值?

I'm using a jSpinner to set the time with format "HH:MM" and it works fine.

My problem is I want to set my jSpinner to "00:00" when the window is activated, and once jSpinner is clicked I want the value to be changed to the "HH:MM" format. And I can't do it myself, the jSpinner value doesn't change it is still "00:00".

Please help me. Thank you in advance.

解决方案

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值