[英]How to properly set time to JSpinner in Java?
我想将Ntbeans的JSpinner设置为当前时间,并允许用户通过单击上下箭头来选择时间。 我有这些代码,这些代码最初以某种方式起作用,但是单击箭头时无法更改时间。 这是我的代码:
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));
当我单击箭头键时,时间不会改变,并显示以下错误消息:
java.lang.ClassCastException: javax.swing.SpinnerNumberModel cannot be cast to javax.swing.SpinnerDateModel
我的代码有什么问题? 我通过网络进行了研究,它们都具有相同的代码。 任何帮助将不胜感激。 谢谢你
什么是mySpinnerControl
? 将mySpinnerControl
更改为spinner
时,可以使您的示例工作。 我的猜测是,您将编辑器设置在另一个组件上,因此spinner
仍然使用Number-Editor,当它尝试设置日期/时间值时,该编辑器会产生异常。
以下代码为我工作:
public class Spinner extends JFrame {
public Spinner() {
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerDateModel());
spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));
getContentPane().add(spinner, BorderLayout.CENTER);
}
public static void main(String[] args) {
Spinner f = new Spinner();
f.pack();
f.setVisible(true);
}
}
..i终于成功了! 我只使用了以下2行代码:
mySpinnerControl.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(mySpinnerControl, "HH:mm"));
但是,非常感谢您的回复@cello和@Radiodef ..非常感谢你们!
在我为JSpinner写作之前,让我告诉您使用以下Date函数。
Date d1 = new Date(0);
Calendar cl = Calendar. getInstance();
cl.setTime(d1);
System.out.println("today is " + d1.toString());
然后是JSpinner,它可以按如下方式使用。将格式更改为仅“ dd”可以给您日期。要操作它,请使用整数解析器(注释行)将其转换。
SimpleDateFormat formaterD = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String spinnerDate=formaterD.format(testSpin.getValue());
//int z=Integer.parseInt(spinnerValue);
System.out.println(spinnerDate);
//System.out.println("Date in integer format:"+z);
//To err is Human!Please comment if I'm wrong.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.