简体   繁体   English

如何将侦听器附加到JavaFX微调器?

[英]How do you attach a listener to a JavaFX spinner?

I've run into what seems (to me, anyway) an odd problem with JavaFX spinners and not being able to attach any kind of listener to it. 我遇到了JavaFX微调器似乎(无论如何对我来说)是一个奇怪的问题,并且无法将任何类型的侦听器附加到它。

I'm used to Swing programming, where I can attach a ChangeListener to a JSpinner and receive events that way, but JavaFX doesn't seem to have anything like that. 我习惯了Swing编程,可以在其中将ChangeListener附加到JSpinner并以这种方式接收事件,但是JavaFX似乎没有这样的东西。

The code in question... 有问题的代码...

    IntegerSpinnerValueFactory spinnerValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, Integer.MAX_VALUE); 

    hullPointsSpinner = new Spinner<Integer>(spinnerValueFactory); 
    hullPointsSpinner.setEditable(true);

    ((TextField)hullPointsSpinner.getEditor()).setOnAction(new EventHandler<ActionEvent>() {

        public void handle( ActionEvent event )
        {
        System.out.println("Howdy, folks!  Value is " + hullPointsSpinner.getValue() + "!!"); 
        }
    });

The arrow buttons will increase and decrease the value in the field, but have no effect on the value in the model. 箭头按钮将增加或减少字段中的值,但对模型中的值没有影响。 Only selecting the contents of the field and pressing enter will actually update the data in the model and prints out the value. 仅选择该字段的内容并按Enter键才能真正更新模型中的数据并打印出该值。 (The pressing enter thing is in the documentation, I know.) (我知道,按Enter键是在文档中。)

I also realize that I'm putting that EventHandler onto the Spinner's TextField with getEditor, but I have yet to see another way to do this. 我还意识到,我已经使用getEditor将EventHandler放置在Spinner的TextField上,但是我还没有看到另一种方式来做到这一点。

Is there a way to hook a listener to the spinner's buttons? 有没有一种方法可以将收听者吸引到微调按钮上?
(Heck, is there even a way to get at those buttons to attach a listener?) (哎呀,有没有办法获得那些按钮来附加一个听众?)

Am I receiving the wrong type event from the spinner/editor? 我是否从微调器/编辑器接收到错误的类型事件? Can I put some kind of listener on the spinnerValueFactory? 我可以在spinnerValueFactory上放置某种侦听器吗?
Is there some kind of obvious solution that I'm overlooking here? 我在这里有什么明显的解决方案吗?

I'll replace this with a JSpinner, if necessary, but it just seems crazy to me that this API would have a spinner component and such an awkward way to use it. 如有必要,我将其替换为JSpinner,但对我而言,该API具有微调组件和如此笨拙的使用方式似乎让我感到疯狂。

Thanks in advance. 提前致谢。

The following seems to work fine for me: 以下似乎对我来说很好:

hullPointsSpinner.valueProperty().addListener((obs, oldValue, newValue) -> 
    System.out.println("New value: "+newValue));

Alternatively you can do 或者你可以做

spinnerValueFactory.valueProperty().addListener(...);

with the same listener as above. 与上面的监听器相同。

You should note this bug , which is fixed in 1.8.0u60. 您应该注意此错误此错误已在1.8.0u60中修复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM