如何在JavaFX的ComboBox中为选项添加值

10

我该如何在组合框的选项中添加一个值,以便当用户选择ComboBox中的项目时,我能够显示该项目的价格?

例如,如果用户选择了一种动物,我可以显示该动物的价格。 如果用户选择dog,那么我可以显示$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());
    }
}

我已经试图修复代码,这就是我得到的结果。还有一些错误,有人知道我做错了什么吗?

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;

}
}

另外,当用户选择动物后,我该如何在组合框下方显示价格? 这样它会说“该动物的价格为”


Java 命名规范请参考。 - kleopatra
1个回答

22

您需要为ComboBox提供一个数据模型,其中存储动物的名称和价格,例如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;
    }
}

然后在您的 ComboBox 中,您可以显示这些 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()));

现在只需要在ComboBox上显示动物的名称而不是对象本身。为了实现这个目标,你可以使用例如StringConverter

comboBox.setConverter(new StringConverter<Animal>() {
    @Override
    public String toString(Animal object) {
        return object.getName();
    }

    @Override
    public Animal fromString(String string) {
        return null;
    }
});

当值发生改变时,输出如下:

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;
        }
    }
}

1
是的,你应该导入javafx.collections.FXCollections - DVarga
我现在有一个错误 animals.java:52: 错误:Animal类为public,应在名为Animal.java的文件中声明 public class Animal { - user6587841
然后按照错误提示做,创建一个 Animal.java 文件并复制类 :) - DVarga
为您添加了完整的示例。请返回翻译后的文本。 - DVarga
你应该使用食品对象完成同样的操作,你已经有了完整的模板。如果你遇到困难,请提出一个单独的问题,包括你的全部代码、错误信息和清晰的描述你想要实现什么,然后你一定会得到帮助。 - DVarga
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接