首页 > 解决方案 > 如何使用 FileChooser 从文件中获取数据(项目 ID、项目名称、项目价格)并在组合框中列出项目 ID?如何将标签与选择匹配?

问题描述

我正在尝试制作销售终端。我需要使用 FileChooser 从文本文件中读取(项目 ID、项目名称和项目价格)。然后 itemID 应该列在一个组合框中。组合框选择应该将标签和价格更改为相应的项目名称和项目价格。我相信这与属性和绑定有关,但我不明白如何使用它们。

我尝试创建一个 Items 类,我尝试将文件读入三个数组,然后将 ID 数组项与组合框选择进行比较,然后将标签文本切换到具有相同位置的名称数组项。

stage.setTitle("Open Resource File");
    FileChooser fileChooser = new FileChooser();
    try { 
        FileReader reader = new 
FileReader(fileChooser.showOpenDialog(stage));
        Scanner scanner = new Scanner(reader);
        for (int i = 0; i < 10; i++) {
            itemID[i] = scanner.next();
            itemName[i] = scanner.next();
            itemPrice[i] = scanner.nextDouble();
        }
        scanner.close();
        reader.close();
        }
    catch (Exception FileNotFoundException) {

    }



Items item = new Items();
    ComboBox idBox = new ComboBox();
    idBox.setPromptText("Select an item");
    idBox.getItems().addAll("A", "B", "C", "D", "E", "F", "G", "H", "I", 
"J");
    idBox.setOnAction(e -> {
        item.setName(idBox.getValue().toString(), itemID, itemName);
        item.setPrice(idBox.getValue().toString(), itemID, itemPrice);
        nameLbl.setText(item.name.toString());
    });

    double quantity;
    Label idLabel = new Label("Item ID: ");
    Label nameLabel = new Label("Item Name: ");
    Label nameLbl = new Label(item.name.toString());
    Label priceLabel = new Label("Item Price: ");
    Label priceLbl = new 
Label(NumberFormat.getCurrencyInstance(newLocale("en", 
"US")).format(item.price));    
    Label priceLbl = new Label("");

Program compiles and main window opens but shows error and crashes when 
it tries to create the point of sales terminal window.

标签: javafxcomboboxpropertiesbindingfilechooser

解决方案


因此,您需要研究许多事情,这不会包含所有代码,但应该足以让您继续前进。

1)您将希望将您的项目扫描到一个ObservableList<Item>列表中,以便将它们放在一个列表中以供使用。至少你可以在你的 for 中做这样的事情:

String id = scanner.next();
String name = scanner.next();
String price = scanner.nextDouble();
items.add(new Item(id, name, price));

尽管您可能希望使扫描仪内的循环更加动态(而不是 10) - 可能使用 while 循环或不同的阅读器。

2)现在您已经有了要使用的项目列表ComboBox<Item> cbItems = new ComboBox<Item>()来显示。您必须设置cbItems.setCellFactory(...)andcbItems.setButtonFactory(...)才能在下拉列表中显示 ID 或名称。然后可以将您添加到的 ObservableList 设置为cbItems.setItems(items)(1) 中所述。有大量关于这样做的 SO 文章,所以我将省略完整的代码。

3) 经销商可以选择是否要使用ObjectProperty<Item>cbItems.selectedProperty()绑定到您正在使用的文本框。'd 建议从你现在使用的 on change 处理程序开始,并直接使用设置标签item.getName(),一旦你开始工作,就转到lblName.textProperty().bind(Bindings....).

关于错误,您没有发布足够的信息(异常是什么,或者要复制的完整代码),所以我无法提供帮助。但是,如果您研究上述项目,您应该更接近。


推荐阅读