为什么列表显示的是包裹而不是实际值?

问题描述 投票:0回答:1

我试图仅显示订单窗口中的商品名称,这就是我所拥有的

ListView<MenuItem> orderList = new ListView<>();

public OrderWindow() {
    
    myStage = new Stage();
    GridPane gridpane = new GridPane();
    VBox vbox = new VBox(gridpane);
    Scene scene = new Scene(vbox);
    Label orderLabel = new Label("Items");
    gridpane.add(orderLabel, 0, 0);
    gridpane.add(orderList, 1, 0);
    myStage.setTitle("Order Window");
    
    gridpane.add(addSelect, 1, 4);
    gridpane.add(placeOrder, 2, 4);
    gridpane.add(cancelOrder, 3, 4);
    
    addSelect.setOnAction(this);
    placeOrder.setOnAction(this);
    cancelOrder.setOnAction(this);
    
    
    myStage.setScene(scene);
    
    
}

public void show(Cafe c) {
    cafe = c;

    
    //ObservableList<MenuItem> list = FXCollections.observableArrayList(c.getAllMenuItems());
    
    
    orderList.getItems().setAll(c.getAllMenuItems());
    
    orderList.getSelectionModel().select(0);
    
    
    
    
    myStage.showAndWait();
}'`

当我执行时,这就是我得到的

enter image description here

这是我的咖啡课:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

public class Cafe {

    private ArrayList<MenuItem> menuItems = new ArrayList<>();
    private String[] itemTypes = {"Bakery", "Beverage", "Sandwich"};
    private ArrayList<Order> placedOrderList = new ArrayList<>();
    private ArrayList<Order> pendingOrderList = new ArrayList<>();

    /**
     * Initializes the Cafe object.  Loads the cafe from the provided
     * configuration file.
     * @param configPath Path to the configuration file
     * @throws FileNotFoundException
     */
    public Cafe(String configPath) throws FileNotFoundException {
        loadItems(configPath);
    }

    private void loadItems(String configPath) throws FileNotFoundException {
        Scanner input = new Scanner(new File(configPath));
        int lineNum = 1;
        while (input.hasNext()) {
            try {
                String line = input.nextLine();
                String[] fields = line.split(",");
                String type = fields[0];
                String name = fields[1];
                MenuItem item;
                double price = Double.parseDouble(fields[2]);
                if (Arrays.asList(itemTypes).contains(type)) {
                    item =  new MenuItem(type, name, price);
                    menuItems.add(item);
                } else {
                        System.err.printf("Unknown type: %s%n", type);
                }
            } catch (Exception e) {
                System.err.printf("Error on line %d: %s%n", lineNum, e.getMessage());
            }
            lineNum++;
        }
        input.close();
    }
    
    public List<Order> getOrderList() {
        return Collections.unmodifiableList(placedOrderList);
    }

    /**
     * Adds a line to the specified order.
     * @param orderId The id of the order to which this item is to be added.
     * @param itemName The name of the item, from the SalesItem
     * @param numOrdered The number of this type items ordered.
     */
    public void addLineItem(int orderId, String itemName, int numOrdered) {
        Optional<Order> order = findPendingOrder(orderId);
        if (order.isPresent()) {
            Optional<MenuItem> item = findItemByName(itemName);
            if (item.isPresent()) {
                order.get().addItem(item.get(), numOrdered);
            }
        }
    }
    
    private Optional<MenuItem> findItemByName(String itemName) {
        Optional<MenuItem> foundItem = Optional.empty();
        for (MenuItem item : menuItems) {
            if (itemName.equalsIgnoreCase(item.getName())) {
                foundItem = Optional.of(item);
                break;
            }
        }
        return foundItem;
    }

    /**
     * Get the categories of items offered by the cafe.
     * @return The categories as an array of strings.
     */
    public List<String> getMenuItemTypes()  {
        return new ArrayList<String>(Arrays.asList(itemTypes));
    }
    
    /**
     * Get all of the items on the menu.
     * @return A List containing all of the items.
     */
    public List<MenuItem> getAllMenuItems() {
        return Collections.unmodifiableList(menuItems);
    }
    
    /**
     * Get the items on the menu limited to a particular category.
     * @param type The category, e.g. Bakery.
     * @return A list of items matching the category.
     */
    public List<MenuItem> getMenuItemsByType(String type) {
        List<MenuItem> items = new ArrayList<>();
        for (MenuItem item : menuItems) {
            if (type.equalsIgnoreCase(item.getType())) {
                items.add(item);
            }
        }
        return items;
    }

    public Optional<MenuItem> getMenuItemByName(String itemName) {
        return findItemByName(itemName);
    }

    /**
     * Creates a new pending Order to hold items added by the user.  The
     * returned order id is to be used when adding to the order, placing the
     * order or canceling the order. @return The order id of the newly created
     * order.
     */
    public int startOrder() { 
        Order order = new Order();
        pendingOrderList.add(order);
        return order.getOrderId();
    }
    
    /**
     * Confirm that the order is being placed.
     * @param id The id of the order being placed.
     */
    public void placeOrder(int id) {
        Optional<Order> order = findPendingOrder(id);
        if (order.isPresent()) {
            placedOrderList.add(order.get());
        }
    }

    /**
     * Cancel the order.
     * @param id The id of the order being canceled.
     */
    public void cancelOrder(int id) {
        Optional<Order> order = findPendingOrder(id);
        if (order.isPresent()) {
            pendingOrderList.remove(order.get());
        }
    }
    
    private Optional<Order> findOrderById(ArrayList<Order> list, int id) {
        return list.stream()
                   .filter(e -> e.getOrderId() == id)
                   .findAny();
    }

    /**
     * Find the pending order based on the given id.
     * 
     * @param id The id of the pending order to be found.
     * @return an Optional containing the order if it is found; otherwise, and empty Optional.
     */
    public Optional<Order> findPendingOrder(int id) {
        return findOrderById(pendingOrderList, id);
    }
    
    /**
     * Find the placed order based on the given id.
     * 
     * @param id The id of the placed order to be found.
     * @return an Optional containing the order if it is found; otherwise, and empty Optional.
     */
    public Optional<Order> findPlacedOrder(int id) {
        return findOrderById(placedOrderList, id);
    }
    
    // for debugging only
    public void displayOrders() {
        for (Order order : placedOrderList) {
            System.out.printf("Order # %d%n", order.getOrderId());
            for (OrderItem item : order.getOrderedItems()) {
                System.out.println(item);
            }
        }
    }
}

我尝试将数组列表更改为可观察列表,然后将其添加到列表视图中,但它不起作用。如果有人可以帮助我解决这个问题,我将不胜感激。

oop javafx arraylist
1个回答
0
投票

前言

课程

MenuItem
并不适合您想要实现的目标,而且您不会对此感到满意。

您需要告诉您的ListView:亲爱的ListView,请按照我为您定义的方式显示您的项目。

您需要为此创建一个自定义单元工厂。

解决方案

只需将

Employee
替换为您的班级即可。

ListView<Employee> listView = new ListView<>();
listView.setCellFactory(new Callback<ListView<Employee>, ListCell<Employee>>() {
    @Override
    public ListCell<Employee> call(ListView<Employee> param) {
        return new ListCell<Employee>() {
            
            @Override
            protected void updateItem(Employee item, boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item.getName()); // this is the String which is displayed in the ListView
                }
            }
        };
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.