shaydoe shaydoe - 1 year ago 262
Java Question

How to set text in a JavaFX choice box based on selected row in a table

I am developing a ticketing system using JavaFx. When the user selects a particular ticket in the table and clicks the "Edit" button, the data in the selected row is loaded into the corresponding fields in the form below. The user can then make changes and update the information.

Image showing the GUI I am referring to

However, I am having problems figuring out how to set the text in the choice boxes for "Status" and "Severity" to the text in the selected row. This is the code I have for the edit button so far:

private void editButtonFired(ActionEvent event) {
try {
int value = table.getSelectionModel().getSelectedItem().getTicketNum();

JdbcRowSet rowset = RowSetProvider.newFactory().createJdbcRowSet();
rowset.setCommand("SELECT * FROM s_fuse_ticket_table WHERE ticket_id = ?");
rowset.setInt(1, value);

while( {
}catch (SQLException e){


I tried using the .setSelectionModel() method but that didn't work. Could someone please assist me?
Thank you!

Answer Source

Call choiceBox.setValue() to set the value of the choice box:

import javafx.scene.control.ChoiceBox;

ChoiceBox cb = new ChoiceBox();
cb.getItems().addAll("item1", "item2", "item3");

Answers to follow-up questions

So I have already set the values for the choice box in the fxml

Probably not. Probably you have set the items and not the value (which is fine). For your use case, you couldn't set the value in FXML because the value is not known until the user selects the related line item in your master table.

When I try to use the setValue() method to set the value retrieved from the table I get an error saying: incompatible types: String cannot be converted to CAP#1 where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of

I have never experienced such an error message before. For what it is worth, there is some info on it here: incompatible types and fresh type-variable, though I confess I do not directly see the relevance to your situation. My guess is that you are not defining the type of items for the ChoiceBox or are defining them as something other than a String. You can set the type explicitly using:

ChoiceBox<String> cb = new ChoiceBox<>();

As you are using FXML, the choicebox definition would not use the new keyword and would just be similar to below:

ChoiceBox<String> cb;

If the type of your ChoiceBox is something other than String, then you may need to set a converter on it.

There are too many unknowns from your question to provide a more specific answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download