我想用当前时间将我的JSpinner设置为Neatbeans swing,并允许用户通过单击上下箭头来选择时间。我有这些代码在某种程度上起作用,但无法改变点击箭头的时间。这是我的代码:
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
我的代码出了什么问题?我通过网络研究,他们都有相同的代码。 任何帮助将不胜感激。 谢谢。
答案 0 :(得分:2)
什么是mySpinnerControl
?当我将mySpinnerControl
更改为spinner
时,我可以让您的示例正常工作。我的猜测是你将编辑器设置在另一个组件上,因此spinner
仍然使用数字编辑器,然后在尝试设置日期/时间值时产生异常。
以下代码对我有用:
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);
}
}
答案 1 :(得分:0)
..我终于让它奏效了!我刚使用了以下2行代码:
mySpinnerControl.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(mySpinnerControl, "HH:mm"));
但是非常感谢你的回复@cello和@Radiodef ..非常感谢你们!
答案 2 :(得分:0)
在我为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.