Javafx ListView在项目上第一次单击时调用equals(null)

时间:2017-11-23 02:02:42

标签: java listview javafx null

我有这个非常简单的课程:

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class App extends Application {
    @FXML
    private ListView<CustomObj> listView;

    class CustomObj {
        @Override
        public boolean equals(Object obj) {
            System.out.println("equals " + obj);

            if (obj != null) {
                if (super.equals(obj))
                    return true;
                if (obj.getClass() == getClass())
                    return true;
            }

            return false;
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("layout.fxml"));
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @FXML
    public void initialize() {
        ObservableList<CustomObj> list = FXCollections.observableArrayList();
        list.addAll(new CustomObj(), new CustomObj());
        listView.setItems(list);
    }

    @FXML
    void itemClicked(MouseEvent event) {
        System.out.println("clicked " + listView.getSelectionModel().getSelectedItem());
    }

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

这是使用过的FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="337.0" prefWidth="314.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="a.b.c.App">
   <children>
      <ListView fx:id="listView" layoutX="57.0" layoutY="69.0" onMouseClicked="#itemClicked" prefHeight="200.0" prefWidth="200.0" />
   </children>
</AnchorPane>

当我点击ListView中的一个项目时会发生奇怪的行为,它看起来像是调用了item.equals(null),我不知道它为什么调用equals()但事实是传递的参数是null,至少这种情况只在我第一次点击某个项目时发生。如果我使用ListView of String而不是CustomObj,则不会发生这种情况。当我点击时,知道为什么以及谁调用equals()?

0 个答案:

没有答案