如何打开按选定的列表视图项过滤的信息窗口

时间:2019-07-14 23:26:57

标签: java javafx scenebuilder

我正在为一个学校的项目做一个比赛管理器,其中有3个listViews(1个用于锦标赛,1个用于团队,1个用于玩家)。目前,我正在尝试从playersLV中选择一个玩家,然后单击一个按钮,该按钮将打开一个弹出窗口,其中包含有关该玩家的详细信息,例如全名,年龄等。不幸的是,抛出了空指针异常,并且很可能是是未返回的选定项目。

我尝试在initialize方法的内部和外部初始化Player变量。

最重要的代码:

public class HomepageController {

    Player player = new Player(null, "Joao Costa", 23);
    @FXML
    private ListView<Player> playerLV;
    private ObservableList<Player> players = FXCollections.observableArrayList();

    @FXML
    private void initialize() {
        players.add(player);
        playerLV.setItems(players);
    }

    @FXML
    void seePlayerInfo(ActionEvent event) throws IOException {
        System.out.println("Player Info Button");
        System.out.println();

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/PlayerInfo.fxml"));
        Parent root = loader.load();
        Scene scene = new Scene(root);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.setTitle("Player Info");
        stage.showAndWait();
    }

    public Player getSelectedPlayer() {
        return playerLV.getSelectionModel().getSelectedItem();
    }
}

这是弹出窗口的控制器:

public class PlayerInfoController {

    HomepageController hc = new HomepageController();
    Player player;
    @FXML
    private Label nameLB;
    @FXML
    private Label ageLB;

    @FXML
    private void initialize() {
        player = hc.getSelectedPlayer();
        nameLB.setText(player.getName());
        ageLB.setText(String.valueOf(player.getAge()));

    }
}

这是控制台中的最后一条错误消息:

Caused by: java.lang.NullPointerException
    at controllers.HomepageController.getSelectedPlayer(HomepageController.java:200)
    at controllers.PlayerInfoController.<init>(PlayerInfoController.java:16)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
    at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    ... 65 more

0 个答案:

没有答案