There is a table in MySQL with two columns: ID and name. Interaction with the database is carried out through Hibernate.

I write down the name in ChoiceBox:

private void champBox(){ Session session = sf.openSession(); List<ChampClass> list = (List<ChampClass>) session.createQuery("from ChampClass").list(); Iterator<ChampClass> itr=list.iterator(); while(itr.hasNext()){ ChampClass q=itr.next(); champSetChoiceBox.getItems().add(q.getName()); } session.close(); } 

ChampClass:

  @Entity public class ChampClass { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "name") private String name; public ChampClass(Integer id, String name){ this.id = id; this.name = name; } public ChampClass(){ } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 

In ChoiceBox, you need to pass the name list, and you must, when choosing, receive the ID value in variable for writing to another table.

I assume that you need to make a listener, but I don’t know how to implement it. This listener only reads the ChoiceBox value:

 ChangeListener<String> changeListener = new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, // String oldValue, String newValue) { } }; champSetChoiceBox.getSelectionModel().selectedItemProperty().addListener(changeListener); 

    1 answer 1

    1. Make your ChoiceBox consist of ChampClass Elements, and redefine ChampClass to String to getName.
     ChoiceBox<ChampClass> chBox = new ChoiceBox(); 
      @Entity public class ChampClass { ... @Override public String toString() { return getName(); } } 
    1. And in the listener you can already take id

    choiceBox.getSelectionModel (). selectedItemProperty (). addListener ((obs, oldValue, newValue) -> {System.out.println (newValue.getId ()); System.out.println (newValue.getName ());})) ;

    • Thank you, everything turned out so simple, and I was puzzled for so long. - Vladimir