简体   繁体   中英

Getting information about a cell in a javafx listview

I have a Listview, made with Fxml and elements within it were added via an observable list. I want to, when the user double clicks a node, to get data about that node . I already dealt with the double click and everything else, but I need to get the name of the clicked node to be able to get data from a hashmap and so on... I tried to use if(e.getTarget() == ListCell) but it tells me "Expression expected" as if it was an enum.

I know there might be a duplicate of this somewhere, but I couldn't find any with my formulation of the question... So, I'm asking you, how do I get the name of the node and check if the click happened on a node or in the "void of the listview".

Edit: By name, I mean display name.

Here is one way to accomplish what I think you are asking. This uses setOnMouseClicked in the setCellFactory .

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ListViewExperiments extends Application
{

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        primaryStage.setTitle("ListView Experiment 1");

        Label label = new Label("Hello World!");

        ListView<Person> listView = new ListView();
        listView.setCellFactory(lv -> new ListCell<Person>()
        {
            @Override
            public void updateItem(Person item, boolean empty)
            {
                super.updateItem(item, empty);
                if (empty) {
                    setText(null);
                    setOnMouseClicked(null);
                }
                else {
                    setText(item.getFirstName() + " " + item.getLastName());
                    setOnMouseClicked(event -> {
                        if (event.getClickCount() == 2) {
                            label.setText(item.getFirstName() + item.getLastName());
                        }
                    });
                }

            }
        });

        listView.getItems().add(new Person("a", "b"));
        listView.getItems().add(new Person("c", "d"));
        listView.getItems().add(new Person("e", "f"));

        VBox vBox = new VBox(listView, label);

        Scene scene = new Scene(vBox, 300, 120);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        Application.launch(args);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM