Вопрос

   try {
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/project?"
                        + "user=root&password=virus");
        statement = connect.createStatement();

        preparedStatement = connect
                .prepareStatement("select subname from subject");
        rs=preparedStatement.executeQuery();

        while (rs.next()) {
            subject = rs.getString("subname");
            ObservableList<String> options1 = FXCollections.observableArrayList(subject);
            comboBox1 = new ComboBox(options1);
        }
        } catch (ClassNotFoundException | SQLException e) {
        throw e;
    } finally {
        close2();
    }

    comboBox1.setPromptText("Select Subject");
    comboBox1.setPrefSize(280, 30);

This is my code to read some multiple values from a table and display it in a ComboBox. Actually there are 3 values to be displayed. The while loop is working fine. Each time it reads each value from the table and place it in the ComboBox.

But when the next value is comes, it overlaps the previous value and as a result only one value is displayed in the ComboBox, that is the last read value. But I need to display all the values in the ComboBox, that is when a new value comes, I need to add it as a new entry, instead of overlapping the previous value.

How can I do it ?

Это было полезно?

Решение

The value-property is for the currently selected item. You have to add the results to the items-ObservableList instead:

List items = comboBox1.getItems(); // java.util.List by the way
items.add("item1"); // use the values from result set here instead
items.add("item2");
//...

If you want to show the prompt text, use this:

comboBox1.setPromptText("your prompt text");

Of course you don't create a ComboBox for each row in the ResultSet but one for all rows:

//...
rs = preparedStatement.executeQuery();
ArrayList<String> subnames = new ArrayList<>();

// add all "subname" values to a List
while (rs.next()) {
    subnames.add(rs.getString("subname"));
}

// create a ObservableList from the subnames List
ObservableList<String> options1 = FXCollections.observableArrayList(subnames);
comboBox1 = new ComboBox(options1);
//...
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top