JSpinnerに設定したSpinnerDateModelの各日付フィールドに増減サイズを指定する
Total: 3201, Today: 1, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JSpinnerにSpinnerDateModelを設定し、スピンボタンをクリックした際の増減サイズを各日付フィールドごとに指定します。
Screenshot

Advertisement
Source Code Examples
HashMap<Integer, Integer> stepSizeMap = new HashMap<>();
stepSizeMap.put(Calendar.HOUR_OF_DAY, 1);
stepSizeMap.put(Calendar.MINUTE, 1);
stepSizeMap.put(Calendar.SECOND, 30);
stepSizeMap.put(Calendar.MILLISECOND, 500);
JSpinner spinner2 = new JSpinner(new SpinnerDateModel(d, null, null, Calendar.SECOND) {
@Override public Object getPreviousValue() {
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int calendarField = getCalendarField();
int stepSize = Optional.ofNullable(stepSizeMap.get(calendarField)).orElse(1);
cal.add(calendarField, -stepSize);
Date prev = cal.getTime();
return prev;
}
@Override public Object getNextValue() {
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int calendarField = getCalendarField();
int stepSize = Optional.ofNullable(stepSizeMap.get(calendarField)).orElse(1);
cal.add(calendarField, stepSize);
Date next = cal.getTime();
return next;
}
});
View in GitHub: Java, KotlinDescription
Calendar.MINUTEやCalendar.SECONDなどの各日付フィールドごとに増加、減少のステップサイズを指定したHashMapを作成SpinnerDateModel#getNextValue()とSpinnerDateModel#getPreviousValue()の内部でこのHashMapを参照してJSpinnerのスピンボタンなどでの値変更に利用- 上記のサンプルでは秒フィールドにカーソルがある場合は
30秒、ミリ秒の場合は500ミリ秒、マッピングされていないフィールドの場合は1ずつ増減
- 上記のサンプルでは秒フィールドにカーソルがある場合は