You should provide a data model to the ComboBox
which stores the name and the price of the animal, for example instances of the class Animal
.
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 your ComboBox
you can display these Animal
instances:
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()));
The only thing left to display the name of the animals on the ComboBox
rather than the objects itself. To achieve this, you can use for example a StringConverter
:
comboBox.setConverter(new StringConverter<Animal>() {
@Override
public String toString(Animal object) {
return object.getName();
}
@Override
public Animal fromString(String string) {
return null;
}
});
On value change, the output is like:
Price of the Cat is : 23.23
Price of the Dog is : 30.12
Price of the Bird is : 15.0
An 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;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…