I am using JSpinner
for selecting time in HH:MM:SS format. Whenever
i open the GUI the spinner sets automatically to current system time,
What I need is say for example if I click save after giving some value to spinner and when
I again open it the old values should be shown.
I have tried following code but its not working,
if(Stime != null){
Date time = new SimpleDateFormat("HHMMSS", Locale.ENGLISH).parse(Stime);
StarttimeSpinner.setValue(time);
}
where Stime is the previously saved time in HHMMSS format e.g(142030)
is it correct? or how can i do it? Please help!
EDIT:
SpinnerModel Startmodel = new SpinnerDateModel();
StarttimeSpinner = new JSpinner();
StarttimeSpinner = new JSpinner(Startmodel);
JComponent editor = new JSpinner.DateEditor(StarttimeSpinner, "HH:mm:ss");
StarttimeSpinner.setEditor(editor);
try{
if(!(Stime.equalsIgnoreCase("")))
{
Date time = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH).parse(Stime);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateString = formatter.format(time);
StarttimeSpinner.setModel(new SpinnerListModel(new String[]{dateString}));
}
}
}catch(Exception ie){
System.err.println("in time panel");
}
Stime format is HHmmss and its a string.In dateString(Variable) i get the previous value in HH:mm:ss format but its not being set in Spinner instead showing the system time.
EDIT 2: I have Found out a solution but with a bug,
If my code is like this(1),
StarttimeSpinner = new JSpinner();
SpinnerModel Startmodel = new SpinnerDateModel();
StarttimeSpinner = new JSpinner(Startmodel);
JComponent editor = new JSpinner.DateEditor(StarttimeSpinner, "HH:mm:ss");
StarttimeSpinner.setEditor(editor);
The below piece of code works fine,
Date starttime = new Date();
starttime = (Date)StarttimeSpinner.getValue();
if i change the code like below(2),
Date time = new SimpleDateFormat("HHmmss", Locale.ENGLISH).parse(Stime);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateString = formatter.format(time);
StarttimeSpinner.setModel(new SpinnerListModel(new String[]{dateString}));
where Stime is (e.g)120011
The below piece of code doesn't work fine,
Date starttime = new Date();
starttime = (Date)StarttimeSpinner.getValue();
and throwing Exception as java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at get value statement.
I'm not exactly 100% sure what you're trying to acheive, but take a look at the example below, maybe it will help you out. I use a button to set the date, then another button that pops up a
JOptionPane
that shows the previous date saved from the first button click.With the following code, I was able to achieve this using the a the
SpinnerModel
EDIT
For different formatting, just change the format. If you want in time
"HH:mm:ss"
"hh:mm:ss a"