Reputation: 47
I want to set my JSpinner in Neatbeans swing with the current time, and allow user to choose time through clicking the arrows up and down. I have these code which somehow works at first but cannot change the time when clicking the arrows. Here's my code:
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));
When i click the arrow keys, time wont change and got this error message:
java.lang.ClassCastException: javax.swing.SpinnerNumberModel cannot be cast to javax.swing.SpinnerDateModel
What is wrong with my code? I researched through net and they all have the same code. Any help would be greatly appreciated. Thanks ahead.
Upvotes: 0
Views: 2210
Reputation: 1006
Before I write for JSpinner let me tell you to use Date function as below.
Date d1 = new Date(0);
Calendar cl = Calendar. getInstance();
cl.setTime(d1);
System.out.println("today is " + d1.toString());
Then there is JSpinner which can be used as follows.Changing the format to only "dd" can give you the date.To manipulate it convert it using integer parser(the commented out lines).
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.
Upvotes: 0
Reputation: 47
..i finally make it worked! I just used the following 2 line codes:
mySpinnerControl.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(mySpinnerControl, "HH:mm"));
But thank you really for your response @cello and @Radiodef.. very much appreciated you guys!
Upvotes: 0
Reputation: 5486
What is mySpinnerControl
? I could get your example to work when I changed mySpinnerControl
to spinner
. My guess is that you set the editor on another component, and thus spinner
still uses a Number-Editor which then produces the exception when it tries to set the date/time value.
The following code worked for me:
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);
}
}
Upvotes: 2