javafx 用户界面应用程序无法访问 ArrayList 中的所有值

javafx user-interface app can't access all the values from an ArrayList

所以我正在开发一个 javafx gui,它应该 return 在 ArrayList 输入范围内找到的所有有效值,但它的功能仅对最新添加的值有效, 所以它只是 return 点击按钮时的最新条目,我留下了 gui 的示例图片 我希望这有助于澄清: 因此,如果我添加 2 个不同的注册,2 个品牌和 2 个型号,并尝试通过 regNo 进行按钮搜索,它只适用于最新的条目,而不适用于前一个条目; 我为按钮

保留了 setOnAction 方法的代码
    public void searchByReg(javafx.event.ActionEvent e) {
    // clear the text field from the previous message
    txtOutput.clear();
    // get the car from the user through the car reg
    String carReg = txtReg.getText();
    // method to check if the field its empty
    for (int i = 0; i < cars.size(); i++) {
        if (carReg.equalsIgnoreCase(cars.get(i).getRegNo())) {
            txtOutput.setText("You have selected \n" + cars.get(i));
            carFound = true;
        } else {
            txtOutput.setText("That car is not in our Database");
        }

    }

}

提前感谢您的帮助!!!

试试这个,看起来你每次都覆盖文本直到最后一个有效数字。

    txtOutput.setText("You have selected");
    for (int i = 0; i < cars.size(); i++) {
            if (carReg.equalsIgnoreCase(cars.get(i).getRegNo())) {
                txtOutput.append("\n" + cars.get(i));
                carFound = true;
            }
        }

    if(!carFound) {
       txtOutput.setText("That car is not in our Database");
    }

这不是 JavaFX 问题,而只是一个混乱的搜索循环。

自 Java 8 以来,有更好的方法可以做到这一点。以下内容更简单,更易于阅读和调试:

public class LookupSample {

    record Car(String name, String regNo) {
    }

    public static void main(String[] args) {
        List<Car> cars = List.of(new Car("Mazda", "123"), new Car("Ford", "123"), new Car("Dodge", "789"));
        String carReg = "123";
        String result = cars.stream().filter(car -> car.regNo().equals(carReg)).map(Car::name).collect(Collectors.joining("\n\t ", "You have selected:\n\t", ""));
        System.out.println(result);
        boolean carFound = cars.stream().anyMatch(car -> car.regNo().equals(carReg));
        System.out.println("Car Found? " + carFound);
    }
}