fxml combobox, get the selected value into javafx

有些话、适合烂在心里 提交于 2019-12-05 00:15:43

I think the code you have in your question should work as long as the case of the combobox identifier in the code matches that of your fxml fx:id.

I modified this JavaFX fxml combo box selection demonstration app to add a button with an onAction method to retrieve a value from the combo box using the comboBox getValue() method and it worked fine for me.

Check the case of things, I notice that you say the fx:id is sample, yet in your code you use Sample - and the cases must match otherwise the fxml loader won't inject the node into your controller correctly.

Hard to say if the NullPointerException in your code is related to your combo box value retrieval issue as you don't say what the code at TW_JAVAFX_Undecorator.ButtonController.pruefen(ButtonController.java:60) is or provide full executable code to replicate the issue.

RayFoX

Try this:

String output = Sample.getSelectionModel().getSelectedItem().toString();
System.out.println(output);
Maulik Patel

To get the ComboBox selected value, you can use Sample.getSelectionModel method.

Example:

myComboBox.getSelectionModel().selectedItemProperty()
    .addListener(new ChangeListener<String>() {
        public void changed(ObservableValue<? extends String> observable,
                            String oldValue, String newValue) {
            System.out.println("Value is: "+newValue);
        }
});
hmojica

I was trying to find an answer for this error (which has just happened to me in same conditions) and found this post.
If you actually declared your ComboBox identifier correctly as jewelsea said (If not anyway I think other error would have appeared).

The fact is everything was well declared (no syntax error or compiling error).
The error is in runtime, the event @FXML protected void test(ActionEvent event) is been executing when you fill/add data to your ComboBox.
But value property is not changing since no user input has been detected (I'm assuming you're adding data to your ComboBox somewhere else when you initialize the Scene).
So getValue() is returning null.

In this case the line which broken the code is:

System.out.println(output);

Because output is null.

Try to put a breakpoint in the beginning of test(ActionEvent event) method.

I expect this help also others.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!