将mysql数据绑定到javafx中的Combobox

时间:2021-10-05 17:03:52

I'm new in javafx I can't come up a solution with this.

我是javafx的新手我无法用这个来解决问题。

I have mysql table people.

我有mysql表的人。

------------------ 
id        |  name  
------------------ 
int,ai,pk | string
------------------

I want to populate data into combobox only the list of name and then every time i click the combobox, the value should be the id. please help me.

我想将数据填充到组合框中仅列出名称,然后每次单击组合框时,该值应为id。请帮我。

2 个解决方案

#1


0  

Try this demo! where, id_value is the related id of the name.

试试这个演示!其中,id_value是名称的相关id。

public class PopulateComboBoxDemo extends Application {

    private ComboBox<String> people = new  ComboBox<>();
    private List<String> ids = new ArrayList<>();

    @Override
    public void start(Stage primaryStage) { 
        this.populateData();

        BorderPane root = new BorderPane(); 
        root.setCenter(people);     
        Scene scene = new Scene(root, 300, 250);

        people.setOnAction(e -> {
            int index = people.getSelectionModel().getSelectedIndex();
            //here is the id_value
            String id_value = ids.get(index);
            System.out.println("The id of " + people.getItems().get(index) + " is : " + id_value);
            //
            //.........
            //
        });     
        primaryStage.setScene(scene);
        primaryStage.show();
    }   

    private void populateData() {
        this.people.getItems().clear();
        this.ids.clear();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");
            String sql = "select name, id from person";
            PreparedStatement st = con.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            int index = 0;
            while(rs.next()) {
                this.people.getItems().add(index, rs.getString("name"));
                this.ids.add(index, String.valueOf(rs.getInt("id")));
                index++;
            }
            con.close();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(PopulateComboBoxDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }   
    public static void main(String[] args) {
        launch(args);
    }   
}

#2


1  

If you're using JPA to manage your relational data then this code should do the job, otherwise you will have to map your table rows to objects first. Good luck !

如果您使用JPA来管理关系数据,那么此代码应该完成工作,否则您必须首先将表行映射到对象。祝好运 !

 List<People> PeopleList = em.createQuery("SELECT p FROM People p").getResultList();
    ObservableList<People> peopleData = FXCollections.observableList(PeopleList);
    PeopleList.add(null);

 yourCombo.setCellFactory((comboBox) -> {
        return new ListCell<People>() {
            @Override
            protected void updateItem(People item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText("Select");
                    yourCombo.getSelectionModel().clearSelection();
                } else {
                    setText(item.getName();
                }
            }
        };
    });


        yourCombo.setConverter(new StringConverter<People>() {
        @Override
        public String toString(People people) {
            if (people == null) {
                return "Select";
            } else {
                return people.getName();
            }
        }

        @Override
        public People fromString(String nameString) {
            return null; // No conversion fromString needed.
        }
    });



    yourCombo.setItems(peopleData);

#1


0  

Try this demo! where, id_value is the related id of the name.

试试这个演示!其中,id_value是名称的相关id。

public class PopulateComboBoxDemo extends Application {

    private ComboBox<String> people = new  ComboBox<>();
    private List<String> ids = new ArrayList<>();

    @Override
    public void start(Stage primaryStage) { 
        this.populateData();

        BorderPane root = new BorderPane(); 
        root.setCenter(people);     
        Scene scene = new Scene(root, 300, 250);

        people.setOnAction(e -> {
            int index = people.getSelectionModel().getSelectedIndex();
            //here is the id_value
            String id_value = ids.get(index);
            System.out.println("The id of " + people.getItems().get(index) + " is : " + id_value);
            //
            //.........
            //
        });     
        primaryStage.setScene(scene);
        primaryStage.show();
    }   

    private void populateData() {
        this.people.getItems().clear();
        this.ids.clear();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","user","password");
            String sql = "select name, id from person";
            PreparedStatement st = con.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            int index = 0;
            while(rs.next()) {
                this.people.getItems().add(index, rs.getString("name"));
                this.ids.add(index, String.valueOf(rs.getInt("id")));
                index++;
            }
            con.close();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(PopulateComboBoxDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }   
    public static void main(String[] args) {
        launch(args);
    }   
}

#2


1  

If you're using JPA to manage your relational data then this code should do the job, otherwise you will have to map your table rows to objects first. Good luck !

如果您使用JPA来管理关系数据,那么此代码应该完成工作,否则您必须首先将表行映射到对象。祝好运 !

 List<People> PeopleList = em.createQuery("SELECT p FROM People p").getResultList();
    ObservableList<People> peopleData = FXCollections.observableList(PeopleList);
    PeopleList.add(null);

 yourCombo.setCellFactory((comboBox) -> {
        return new ListCell<People>() {
            @Override
            protected void updateItem(People item, boolean empty) {
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText("Select");
                    yourCombo.getSelectionModel().clearSelection();
                } else {
                    setText(item.getName();
                }
            }
        };
    });


        yourCombo.setConverter(new StringConverter<People>() {
        @Override
        public String toString(People people) {
            if (people == null) {
                return "Select";
            } else {
                return people.getName();
            }
        }

        @Override
        public People fromString(String nameString) {
            return null; // No conversion fromString needed.
        }
    });



    yourCombo.setItems(peopleData);