You must provide a data model for the ComboBox that stores the name and price of the animal, such as instances of the Animal class.
public class Animal { private String name; private Double price; public Double getPrice() { return price; } public String getName() { return name; } public Animal(String name, Double price) { this.name = name; this.price = price; } }
Then in ComboBox you can display these instances of Animal :
ComboBox<Animal> comboBox = new ComboBox<Animal>(); comboBox.setItems(FXCollections.observableArrayList( new Animal("Dog", 30.12), new Animal("Cat", 23.23), new Animal("Bird", 15.0))); comboBox.valueProperty().addListener((obs, oldVal, newVal) -> System.out.println("Price of the " + newVal.getName() + " is : " + newVal.getPrice()));
It remains only to show the name of the animals on the ComboBox , and not on the objects themselves. For this you can use, for example, StringConverter :
comboBox.setConverter(new StringConverter<Animal>() { @Override public String toString(Animal object) { return object.getName(); } @Override public Animal fromString(String string) { return null; } });
When changing the value, the output is as follows:
Price of the Cat is : 23.23 Price of the Dog is : 30.12 Price of the Bird is : 15.0
MCVE:
public class Animals extends Application { private ComboBox<Animal> comboBox = new ComboBox<>(); private Text textNamePrice = new Text(); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { comboBox.setConverter(new StringConverter<Animal>() { @Override public String toString(Animal object) { return object.getName(); } @Override public Animal fromString(String string) { return null; } }); comboBox.setItems(FXCollections.observableArrayList(new Animal("Dog", 30.12), new Animal("Cat", 23.23), new Animal("Bird", 15.0))); comboBox.valueProperty().addListener((obs, oldVal, newVal) -> { String selectionText = "Price of the " + newVal.getName() + " is : " + newVal.getPrice(); System.out.println(selectionText); textNamePrice.setText(selectionText); }); VBox layout = new VBox(10); layout.setPadding(new Insets(60, 60, 60, 60)); layout.getChildren().addAll(comboBox, textNamePrice); Scene scene = new Scene(layout, 500, 350); primaryStage.setScene(scene); primaryStage.show(); } public class Animal { private String name; private Double price; public Double getPrice() { return price; } public String getName() { return name; } public Animal(String name, Double price) { this.name = name; this.price = price; } } }