Como adiciono um valor aos itens em uma ComboBox no JavaFX
Como posso adicionar um valor aos itens em uma caixa de combinação para que, quando o usuário selecione um item noComboBox
Sou capaz de exibir o preço desse item
Por exemplo. se o usuário selecionar um animal, eu posso exibir o preço desse animal. O usuário selecionadog
então eu posso exibir o preço de$45
.
public class comboBox extends Application {
Stage window;
Scene scene;
Button button;
ComboBox<String> comboBox;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("ComboBox");
button = new Button("Submit");
comboBox = new ComboBox<>();
comboBox.getItems().addAll(
"cat",
"dog",
"bird"
);
comboBox.setPromptText("Please select one");
button.setOnAction(e -> printPrice());
VBox layout = new VBox(10);
layout.setPadding(new Insets(60, 60, 60, 60));
layout.getChildren().addAll(comboBox, button);
scene = new Scene(layout, 450, 350);
window.setScene(scene);
window.show();
}
private void printPrice(){
System.out.println(comboBox.getValue());
}
}
Eu tentei corrigir o código e foi isso que eu consegui. Ainda existem alguns erros. Alguém sabe o que estou fazendo de errado?
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
public class animals extends Application {
Stage window;
Scene scene;
Button button;
ComboBox<String> comboBox;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("ComboBox ");
button = new Button("Submit");
comboBox.setConverter(new StringConverter<Animal>() {
@Override
public String toString(Animal object) {
return object.getName();
}
@Override
public Animal fromString(String string) {
return null;
}
});
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())); }
VBox layout = new VBox(10);
layout.setPadding(new Insets(60, 60, 60, 60));
layout.getChildren().addAll(comboBox, button);
scene = new Scene(layout, 500, 350);
window.setScene(scene);
window.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;
}
}
Além disso, como eu seria capaz de exibir o preço na caixa de combinação depois que o usuário selecionasse um animal? então dizia "o preço desse custo animal"