1

How can I properly populate values from a mysql database to an observableList in javafx? I am using:

ObservableList<String> deptList=FXCollections.observableArrayList("CSE","ME");

to manually populate values to observablelist,but I have no idea how to fetch data from a mysql database and populate into observable list.

TangledUpInBlue
  • 746
  • 4
  • 13
Shersha Fn
  • 1,511
  • 3
  • 26
  • 34

3 Answers3

3

In order to get a List from your mysql database, open a database connection to your mysql database and execute your query. (I'm not going to write this one out for you, because there's plenty of good examples online.) Once you have your ResultSet:

List<String> listOfSomething;
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
    String current = rs.getString("whatever");
    listOfSomething.add(current);
}

You can just get a list from your database and convert it to an observable list:

List listOfSomething = new ArrayList(ofWhatever);
ObservableList<String> observableListOfSomething = FXCollections.observableArrayList(listOfSomething);
TangledUpInBlue
  • 746
  • 4
  • 13
0

This is the code used to populate data intoto a ListView(JavaFX (fxml)).

 private void populateListView {
            try {
                String query = "select * from main_table";
                PreparedStatement prestate = model.getConnection().prepareStatement(query);
                ResultSet result = prestate.executeQuery();

                while (result.next()) {
                    String current = result.getString("title");
                    ObservableList<String> list = FXCollections.observableArrayList(current);
                    listview.getItems().addAll(list);
                }

                prestate.close();
                result.close();     
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
0

Thank you. The answer mentioned in this post is working in my case too. I am using postgres as database.

creating a table view

@FXML private TableView<AccountMaster> detailstable;

I am getting the details from DB and storing it in a generic list.

List<Student> list = DatabaseClient.getInstance().studentDetailsSearch(id,name);

creating observable list of generic type and then setting the list values in observable list.

ObservableList<AccountMaster> searchDetailsList = FXCollections.observableArrayList(list );

setting it in table view

detailstable.getItems().addAll(searchDetailsList); 

With this we can populate values from database into ObservableList in javafx

n4m31ess_c0d3r
  • 3,028
  • 5
  • 26
  • 35
Soumen
  • 1
  • 3