在我的javafx程序中,我拥有一个ObjectProperty来侦听BigDecimal值的更改(如果更改)。
final ObjectProperty<BigDecimal> number = new SimpleObjectProperty<>();
number.addListener((observableValue, oldValue, newValue) -> System.out.println("Do something!"));
现在,我还想监听BigDecimal.signum()方法的值,因为如果仅更改符号,则上面的监听器将不起作用。 我试图创建一个新的ObjectBinding并向它添加一个侦听器,但没有成功。
final ObjectBinding<Integer> signumBinding = Bindings.createObjectBinding(() -> number.getValue().signum());
signumBinding.addListener((observableValue, oldValue, newValue) -> System.out.println("Do anything else!"));
完整代码如下:
import java.math.BigDecimal;
import java.text.NumberFormat;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
public class NumericTextField extends TextField {
private final NumberFormat nf;
private final ObjectProperty<BigDecimal> number = new SimpleObjectProperty<>();
private final boolean negativAllowed;
public final BigDecimal getNumber()
{
return number.get();
}
public final void setNumber(final BigDecimal value)
{
number.set(value);
}
public ObjectProperty<BigDecimal> numberProperty()
{
return number;
}
public NumericTextField()
{
this(BigDecimal.ZERO);
}
public NumericTextField(final BigDecimal value)
{
this(value, NumberFormat.getInstance(), true);
initHandlers();
}
public NumericTextField(final BigDecimal value,
final NumberFormat nf,
final boolean negativAllowed)
{
super();
this.negativAllowed = negativAllowed;
this.nf = nf;
initHandlers();
setNumber(value);
}
private void initHandlers()
{
focusedProperty().addListener((observableValue, oldValue, newValue) -> {
if (!newValue)
{
parseAndFormatInput();
}
});
this.numberProperty().addListener((observableValue, oldValue, newValue) -> setText(nf.format(newValue)));
}
private void parseAndFormatInput()
{
try
{
final String input = getText();
BigDecimal newValue;
if (input == null || input.length() == 0) {
newValue = BigDecimal.ZERO;
} else
{
final Number parsedNumber = nf.parse(input);
newValue = new BigDecimal(parsedNumber.toString());
if (!negativAllowed) {
newValue = newValue.abs();
}
}
setNumber(newValue);
selectAll();
}
catch (final ParseException ex)
{
setText(nf.format(number.get()));
}
}
}
有人可以告诉我如何监听BigDecimal.signum()方法的值吗?
答案 0 :(得分:0)
您在Bindings.createObjectBinding()
调用中缺少依赖项。
您需要使用
Bindings.createObjectBinding(() -> number.getValue().signum(), number)