关于问题的第一部分......我不久前遇到了类似的问题,我需要一个可以管理小时/分钟/秒的微调器。
我编写了 JSpinner 类的新实现,您可以将其用作基础并对其进行更新以获取 Minutes/Seconds/Milliseconds 微调器。我按“原样”与您分享,它符合我的个人需求,但我当然可以改进:
/**
* TimeSpinner
* A implementation of JSpinner that manages
* only the hour/minute part of a date.
* Careful, in consequence the getValue()
* gives you a date based on the 01/01/1970
* ('issue' known about JSpinner).
* => This spinner implements its own model. It allows to fix
* a pb about the tick (the regular model SpinnerDateModel
* increases/decreases hours instead of minutes.
* => It overrides setBackground and make it works (the regular
* JSpinner.setBackground does not).
*
* User: Yannick DECOURTRAY
* Date: 21/06/11
*/
public class TimeSpinner extends JSpinner {
/**
* Constructor
*/
public TimeSpinner() {
Date date = today();
TimeSpinnerModel sm = new TimeSpinnerModel(date, null, null, Calendar.MINUTE);
setModel(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(this, "h:mm a");
setEditor(de);
}
/**
* Calls setBackground on Editor of the spinner
* @see javax.swing.JComponent#setBackground(java.awt.Color)
*/
@Override
public void setBackground(Color bg) {
JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) getEditor();
editor.getTextField().setBackground(bg);
}
/**
* Model class
*/
private class TimeSpinnerModel extends SpinnerDateModel {
/**
* Constructor
* @param value Current date
* @param start Low limite date
* @param end High limit date
* @param calendarField Step of incrementation
*/
public TimeSpinnerModel(Date value,
Comparable start,
Comparable end,
int calendarField) {
super(value, start, end, calendarField);
}
/** @see javax.swing.SpinnerDateModel#getNextValue() */
public Object getNextValue() {
Date currentDate = getDate();
Calendar currentCal = Calendar.getInstance();
currentCal.setTime(currentDate);
int calField = Calendar.MINUTE;//getCalendarField();
// Add calField to currentDate
currentCal.add(calField, 1);
Date newDate = new Date(currentCal.getTimeInMillis());
Date endDate = (Date) getEnd();
if (endDate != null && newDate.after(endDate))
return currentDate;
else
return newDate;
}
/** @see javax.swing.SpinnerDateModel#getPreviousValue() */
public Object getPreviousValue() {
Date currentDate = getDate();
Calendar currentCal = Calendar.getInstance();
currentCal.setTime(currentDate);
int calField = Calendar.MINUTE;//getCalendarField();
// Add calField to currentDate
currentCal.add(calField, -1);
Date newDate = new Date(currentCal.getTimeInMillis());
Date startDate = (Date) getStart();
if (startDate != null && newDate.before(startDate))
return currentDate;
else
return newDate;
}
}
/**
* Gets the today date
*
* @return the today date
*/
private static Date today() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}