I am using couple of JSpinners in my project who display the hour and minutes. When the JSpinner is incremented or decremented i have to save the value to the database. But
You could maintain a "master date" which you re-merge the time value back into on each stateChanged
event.
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new DateSpinner(new Date()));
}
}
public class DateSpinner extends JSpinner {
private Date masterDate;
public DateSpinner(Date date) {
super(new SpinnerDateModel());
this.masterDate = date;
SpinnerDateModel model = (SpinnerDateModel) getModel();
model.setCalendarField(Calendar.HOUR);
setEditor(new JSpinner.DateEditor(this, "hh:mm"));
JFormattedTextField tf = ((JSpinner.DefaultEditor) getEditor()).getTextField();
DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
formatter.setFormat(new SimpleDateFormat("hh:mm"));
setValue(date);
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
Calendar cal = Calendar.getInstance();
cal.setTime(masterDate);
Calendar time = Calendar.getInstance();
time.setTime((Date) getValue());
cal.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
masterDate = cal.getTime();
System.out.println(masterDate);
}
});
}
public String getTime() {
return new SimpleDateFormat("hh:mm").format((Date)getValue());
}
}
}