Java:如何使 JSpinner 显示带有一定偏移量的值
在我的应用程序中,一些值内部的范围从 0 开始。但是用户应该看到这个范围从 1 开始。我认为将这个偏移内容移到演示文稿中是合适的。在本例中它是 JSpinner 组件。这样我就可以在构造函数中指定是否存在偏移量(并非所有值都有偏移量)。但是,如果我将 JSpinner 的 getValue() 或模型的 getValue() 重写为类似的内容(+1 仅用于测试),
public Object getValue() {
Number value = (Number)super.getValue();
Number newValue=value;
if (value instanceof Double){
newValue=value.doubleValue()+1;
}
else if (value instanceof Integer){
newValue = value.intValue()+1;
}
return newValue;
}
它将进入无限循环。我想,它出于某种原因在这里触发了状态更改事件。再次调用getValue
,增加更多,触发事件,增加等等。 怎么解决这个问题呢?谢谢
In my application some values internally have their range from 0. But user should see this range starting from 1. I thought it would be appropriate to move this offseting stuff into presentation. In this case it is JSpinner component. So that I could specify in contructor if there is an offset (not all values have it). But if I override getValue()
of JSpinner or getValue()
of model to be something like that (+1 is just for test)
public Object getValue() {
Number value = (Number)super.getValue();
Number newValue=value;
if (value instanceof Double){
newValue=value.doubleValue()+1;
}
else if (value instanceof Integer){
newValue = value.intValue()+1;
}
return newValue;
}
it goes into infinite loop. I guess, it fires state change event for some reason here. Calls getValue
again, increments more, fires event, increments and so on.
How could this be solved? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要混淆程序的数据模型和旋转器的数字模型;将它们分开。委托给具有正确表示范围 1..n 的私有
SpinnerNumberModel
。提供一个返回所需范围内的值的访问器,0..n–1。是的。
SpinnerModel
服务于JSpinner
视图。如果您的应用程序的模型使用不同的单位,则必须进行一些转换。您必须决定哪里最有意义。作为一个具体示例,此模型的ControlPanel
有一个微调器,可以调整频率Hz,而应用程序的定时器
需要一个以毫秒为单位的周期。Don't mingle your program's data model and the spinner's number model; keep them separate. Delegate to a private
SpinnerNumberModel
having the correct presentation range, 1..n. Provide an accessor that returns values in the desired range, 0..n–1.Yes. The
SpinnerModel
serves theJSpinner
view. If your application's model uses different units, some transformation must occur. You'll have to decide where that makes most sense. As a concrete example, this model'sControlPanel
has a spinner that adjusts a frequency in Hz, while the application'sTimer
requires a period in milliseconds.我认为 CyclingSpinnerListModel 可以这样做
I think that CyclingSpinnerListModel can do that