Swing/BigDecimalSpinnerModel のバックアップ(No.18)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/BigDecimalSpinnerModel へ行く。
- 1 (2014-01-20 (月) 02:06:20)
- 2 (2014-01-20 (月) 14:03:15)
- 3 (2014-01-22 (水) 20:40:01)
- 4 (2014-09-17 (水) 02:21:19)
- 5 (2014-10-21 (火) 01:46:10)
- 6 (2015-11-12 (木) 22:04:59)
- 7 (2017-04-07 (金) 13:51:51)
- 8 (2017-04-26 (水) 13:55:28)
- 9 (2017-06-27 (火) 13:51:02)
- 10 (2018-03-22 (木) 19:26:10)
- 11 (2019-04-15 (月) 15:52:46)
- 12 (2020-05-14 (木) 16:17:07)
- 13 (2021-11-03 (水) 02:27:08)
- 14 (2025-01-03 (金) 08:57:02)
- 15 (2025-01-03 (金) 09:01:23)
- 16 (2025-01-03 (金) 09:02:38)
- 17 (2025-01-03 (金) 09:03:21)
- 18 (2025-01-03 (金) 09:04:02)
- category: swing
folder: BigDecimalSpinnerModel
title: JSpinnerの上下限値をBigDecimalで比較する
tags: [JSpinner, BigDecimal, SpinnerNumberModel]
author: aterai
pubdate: 2014-01-20T02:06:20+09:00
description: JSpinnerで浮動小数点型のモデルを使用する場合、最大値と最小値の比較をBigDecimalで行うよう変更します。
image:
Summary
JSpinner
で浮動小数点型のモデルを使用する場合、最大値と最小値の比較をBigDecimal
で行うよう変更します。
Screenshot

Advertisement
Source Code Examples
class BigDecimalSpinnerModel extends SpinnerNumberModel {
public BigDecimalSpinnerModel(
double value, double minimum, double maximum, double stepSize) {
super(value, minimum, maximum, stepSize);
}
@Override public Object getPreviousValue() {
return incrValue(-1);
}
@Override public Object getNextValue() {
return incrValue(+1);
}
private Number incrValue(int dir) {
BigDecimal value = BigDecimal.valueOf((Double) getNumber());
BigDecimal stepSize = BigDecimal.valueOf((Double) getStepSize());
BigDecimal newValue = dir > 0 ? value.add(stepSize) : value.subtract(stepSize);
BigDecimal maximum = BigDecimal.valueOf((Double) getMaximum());
if (maximum.compareTo(newValue) < 0) {
return null;
}
BigDecimal minimum = BigDecimal.valueOf((Double) getMinimum());
if (minimum.compareTo(newValue) > 0) {
return null;
}
return newValue;
}
}
View in GitHub: Java, KotlinExplanation
- 上:
SpinnerNumberModel
Double
型のSpinnerNumberModel
では最大・最小値の比較にDouble#compare(...)
が使用されているstepSize
に指定した0.1
などが持つ浮動小数点誤差のため、このサンプルのJSpinner
の場合下限(2.0
や29.6
)にダウンボタンで遷移できない- たとえば
29.7 - 29.6 - 0.1 >= 0
はfalse
なのでダウンボタンで29.7
から29.6
に遷移不可
- たとえば
- 下:
BigDecimalSpinnerModel
SpinnerNumberModel#getPreviousValue()
などをオーバーライドして、Double#compareTo(Double)
ではなくBigDecimal#compareTo(BigDecimal)
で最小値との比較を行う
Reference
- JavaFAQ: 浮動小数 float/double
- java - JSpinner not showing minimum value on pressing down arrow - Stack Overflow
- SpinnerNumberModelに上限値を超える値を入力