gpt4 book ai didi

java - JSpinner 返回默认值而不是输入值

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:36 24 4
gpt4 key购买 nike

我有一个JSpinnerSpinnerNumberModel (1, Double.MIN_VALUE, Double.MAX_VALUE, 0.01)

如果我直接输入JSpinner -1000 ,在某个对话框中点击“确定”,得到 spinner.getValue()它将返回“1”而不是 1000。

如果我输入 1000并将焦点转移到其他地方,例如单击 JDialog的空空间并读取值后,它将是正确的= 1000 。如果我用微调器的箭头更改值 - 值也将是正确的。

如何修复Jspinner所以它将支持输入值,而无需在获取其值之前先将焦点转移到其他地方?

Java JDK 1.6.0_23

最佳答案

JSpinner JavaDoc描述了为什么会发生这种情况以及如何解决它。

A JSpinner has a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called the editor. The editor is created by the JSpinner's constructor and can be changed with the editor property. The JSpinner's editor stays in sync with the model by listening for ChangeEvents. If the user has changed the value displayed by the editor it is possible for the model's value to differ from that of the editor. To make sure the model has the same value as the editor use the commitEdit method, eg:

try {
spinner.commitEdit();
}
catch (ParseException pe) {{
// Edited value is invalid, spinner.getValue() will return
// the last valid value, you could revert the spinner to show that:
JComponent editor = spinner.getEditor()
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setValue(spinner.getValue();
}
// reset the value to some known value:
spinner.setValue(fallbackValue);
// or treat the last valid value as the current, in which
// case you don't need to do anything.
}
return spinner.getValue();

关于java - JSpinner 返回默认值而不是输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com