如何将对象传递给不同控制器中的ArrayList(java FX)

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

在JAVA FX中有一个应用程序,其中一个窗口创建一个带保险的客户,另一个窗口带有一个tableView,我想显示有关客户的信息。在tableView窗口中,我还有一个ArrayList。当我关闭注册窗口时,应用程序将客户对象发送到ArrayList。这工作正常,但是当我注册另一个客户保险时,ArrayList似乎在接收新对象之前变空。总结一下,我的ArrayList似乎一次只能容纳一个对象。


//In the registration controller, this code is called when I close the window and pass the customer object

    FXMLDocumentController controller = loader.getController();
    controller.initForsikredeKunder(passedCustomer);

//---------- In the view tableclass private ArrayList = null;

public void initForsikredeKunder (Kunde customer) { if(kundeListe == null) { kundeListe = new ArrayList<Kunde>(); } this.kundeListe.add(customer); }

为什么ArrayList只能容纳一个客户?在我看来,这段代码只生成一个ArrayList,然后只需添加客户,因为它们传递给方法。但是,这种情况并没有发生

javafx fxml
1个回答
0
投票

你似乎有一个拼写错误,所以我认为私有ArrayList = null是真的:

private ArrayList kundeListe = null;

代码看起来很好(我在某些上下文中猜测),虽然有一些事情我会改进。它只在“kundeListe”为空时创建一个新列表 - 因此列表不会被清除。因此,如果您第二次调用initForsikredeKunder(),它所做的只是添加第二个“客户”。

基本上,你可以反复调用initForsikredeKunder(),它会正常工作。

我会重命名initForsikredeKunder来说“添加”而不是init。它实际上是一个添加操作,它还处理后备列表的延迟初始化。

更进一步,你可以这样做:

private List<Kunde> kundeListe = new ArrayList<>();

并删除惰性初始化:

public void addKunder (Kunde customer) {
    kundeListe.add(customer);
}

注意:我不是100%我理解你上面的叙述,所以我可能会误解正在发生的事情。如果这个“对话框/窗口”只与单个客户合作,您甚至不需要使用列表!

提供额外信息后进行编辑:

根据您的代码,它看起来像原始对话框没有被重用。 “新的FXMLLoader()”部分没问题。

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("FXMLDocument.fxml"));
Parent tableViewParent = loader.load();
Scene tableViewScene = new Scene(tableViewParent); //Access the controller and call the method
FXMLDocumentController controller = loader.getController();
controller.initForsikredeKunder(valgtKunde); // having trouble finding what it should say instead of = new FXMLLoader();

因此,如果您的对话需要多个客户,最简单的方法就是使用initForsikredKunder()调用传递多个。

这个怎么样?

public void initForsikredeKunder (Kunde... customer) {
    if(kundeListe == null) {
        kundeListe = new ArrayList<Kunde>();
    }
    for (Kunde cust : customer) {
        this.kundeListe.add(cust);
    }
}

然后将initForsikredeKunder()调用更改为:

controller.initForsikredeKunder(valgtKunde1, valgtKunde2, valgtKunde3);//Add as many as you need

如果您已经有一长串“valgtKunde”:

public void initForsikredeKunder (List<Kunde> customers) {
    if(kundeListe == null) {
        kundeListe = new ArrayList<Kunde>();
    }
    this.kundeListe.addAll(customers);
}

...并将列表传递给initForsikredeKunder(customerList);

这是更大的背景重要的事情,遗憾的是我很难在这里传达所有这些,因此根据更广泛的背景可能需要进行一些调整。 (即您开始使用的数据以及对话框功能支持的内容)

© www.soinside.com 2019 - 2024. All rights reserved.