0
votes

I´ve got a problem with JavaFX.

What I try to do is quite simple: 1. The user fill in two TextField with the given name and surename. 2. By cliking at a Button "add person" an Objekt of class "Person" will be added to an arraylist containing the name of the person. At the same time there will be a VBox-Object which adds a anonymus label-Object with the name of the person.

The problem: Now I would like to click on the anonymus label in the VBox and receive back the Person-Object.

Here is the method to add a Person

      btnAddContact.setOnAction(e -> {
        if (!"".equals(tfVorname.getText().toString())
                && !"".equals(tfNachname.getText().toString())) {
            contactList.addContact(new Contact(tfVorname, tfNachname));
            spContacts.setContent(refreshContactList());
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    });

The refreshContactList-method adds the new anonymus Label into the ContactList (an ArrayList) and displays the name in the label:

    private VBox refreshContactList() {

    if (contactList.getContactList().size()>0) {
        vbContacts.getChildren().add(new Label(contactList.getContactList().get(contactList.getContactList().size()-1).getVorname() + " " + contactList.getContactList().get(contactList.getContactList().size()-1).getNachname()));            
    }


    return vbContacts;
}

I tried to program a vbContacts.setOnMouseClicked... but the only object I could receive was the VBox.

Any ideas how to get access to the labes?

Thanks

Karl

1
Just a comment: you might want to learn about ListView.James_D

1 Answers

1
votes

Just add the listener to the label when you create it:

private VBox refreshContactList() {

    if (contactList.getContactList().size()>0) {
        Contact lastContact = contactList.getContactList().get(contactList.getContactList().size()-1);
        Label label = new Label(lastContact.getVorname() + " " + lastContact.getNachname()) ;
        label.setOnMouseClicked(e -> {
            // do whatever you need with lastContact and/or label...
        });
        vbContacts.getChildren().add(label);            
    }


    return vbContacts;
}