从javaFX 8中的ListView保存和加载项时出错[重复]

时间:2021-12-18 16:59:33

This question already has an answer here:

这个问题在这里已有答案:

I have a listView inside which i'm displaying an item of type Card.After closing the application I want to extract those Card objects and save them to a .txt file.However, it seems like the List testingList and ListPropeprty listProperty are empty and this is-from what I understand- the reason why I get a NullPointerException.I've tried figuring this whole error thing out but I am overwhelmed.Hopefully someone here can help me:

我有一个listView,其中我正在显示一个类型为Card的项目。关闭应用程序后,我想提取那些Card对象并将它们保存到.txt文件。但是,似乎List testingList和ListPropeprty listProperty为空并且这是 - 从我的理解 - 我得到NullPointerException的原因。我试图搞清楚这整个错误的事情,但我不知所措。希望有人在这里可以帮助我:

Here is my Card.java:

这是我的Card.java:

package com.spdesigns.dokkancardspreview.model;

import javafx.scene.image.Image;

public class Card {

private String mName;
private String mDescription;
private Image mMainImage;
private Image mSecondaryImage;
private String mMainImagePath;
private String mSecondaryImagePath;

public Card(String name, String description, Image mainImage, Image secondaryImage) {
    mName = name;
    mDescription = description;
    mMainImage = mainImage;
    mSecondaryImage = secondaryImage;
}

public Card(String name, String description , String mainImagePath, String secondaryImagePath) {
    new Card(name,description,new Image(mainImagePath),new Image(secondaryImagePath));
}

@Override
public String toString() {
    return mName + " | " + mDescription;
}

public Image getmMainImage() {
    return mMainImage;
}

public Image getmSecondaryImage() {
    return mSecondaryImage;
}

public String getName() {
    return mName;
}

public String getDescription() {
    return mDescription;
}

}

Here is my home.java(controller):

这是我的home.java(控制器):

package com.spdesigns.dokkancardspreview.controllers;

import com.spdesigns.dokkancardspreview.model.Card;

import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.io.*;
import java.util.List;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class home implements Initializable {

private Card hit = new Card("Hit","Expanding Possibility",
        new Image("/images/hit_main.jpg") , new Image("/images/hit_secondary.jpg"));

private boolean clickedAgain = false;

@FXML
private Button arrowButton;
@FXML
private ImageView imageView;

@FXML
private ImageView arrow;

@FXML
private ListView listView;

protected List<Card> testingList = new ArrayList<Card>();

    protected ListProperty<Card> listProperty = new SimpleListProperty<Card>();


@Override
public void initialize(URL location, ResourceBundle resources) {
    addCard(hit);
    //testingList.add("test2");

    listView.itemsProperty().bind(listProperty);
    // wrapping our list in an observable list and then pass that observableList to the ListProperty isntance
    listProperty.set(FXCollections.observableArrayList(testingList));

    // Handle listView selection changes
    listView.getSelectionModel().selectedItemProperty().addListener(((observable, oldValue, newValue) -> {
        System.out.println("ListView item clicked!");
        imageView.setImage(new Image(hit.getmMainImage().impl_getUrl()));
        arrow.setVisible(true);
        arrowButton.setVisible(true);
    }));

    arrow.translateYProperty().set(283f);
    arrowButton.translateYProperty().set(283f);
    arrow.setRotate(180);
    arrow.setVisible(false);
    arrowButton.setVisible(false);
}

public void handleShowDetails(ActionEvent actionEvent) {
    System.out.println("Button Clicked!");
    if(clickedAgain) {
        imageView.setImage(new Image(hit.getmMainImage().impl_getUrl()));
        arrow.setRotate(180);
        clickedAgain = false;
    } else {
        imageView.setImage(new Image(hit.getmSecondaryImage().impl_getUrl()));
        arrow.setRotate(360);
        clickedAgain = true;
    }
}

// Saving
public void exportTo(String fileName) {
    try(
            FileOutputStream fos = new FileOutputStream(fileName);
            PrintWriter writer = new PrintWriter(fos);
    ){
        for(Card card : testingList) {
            writer.printf("%s|%s|%s|%s/n",card.getName(),card.getDescription(),
                    card.getmMainImage().impl_getUrl(),card.getmSecondaryImage().impl_getUrl());
        }
    } catch (IOException ioe) { // If the file couldn't be opened
        System.out.printf("Problem saving: %s/n", fileName);
        ioe.printStackTrace();
    }
}

// Loading
public void importFrom(String fileName) {
    try(
            FileInputStream fis = new FileInputStream(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
    ){
        String line;
        while((line = reader.readLine()) != null) {
            String[] args = line.split("\\|");
            this.addCard(new Card(args[0],args[1],args[2],args[3]));
        }
    } catch (IOException ioe) {
        System.out.printf("Problem loading: %S/n" , fileName);
        ioe.printStackTrace();
    }
    System.out.printf("%s loaded",testingList.get(0).toString());
}

public void addCard(Card card) {
    testingList.add(card);
}

public void printTestingList() {
    for (Card card : testingList) {
        System.out.println(card.toString());
    }
}

}

My Main.java:

package com.spdesigns.dokkancardspreview;

import com.spdesigns.dokkancardspreview.controllers.home;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.File;

public class Main extends Application {

private home controller;
private File file = new File("CardsCollection.txt");

@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/home.fxml"));
    primaryStage.setTitle("Dokkan Battle Card Preview");
    primaryStage.setScene(new Scene(root, 900, 700));
    primaryStage.setResizable(false);
    // Loading cards
    primaryStage.show();
    try {
        if(!file.exists()) {
            file.createNewFile();
        }
        controller.importFrom("CardsCollection.txt");
    } catch (NullPointerException npe) {
        System.out.println("Error loading file!");
        npe.printStackTrace();
    }
}

@Override
public void stop() {
    System.out.println("App is closing!");
    // Saving before exiting
    try {
        controller.exportTo("CardsCollection.txt");
    } catch (NullPointerException npe) {
        System.out.println("Problem saving file!");
        npe.printStackTrace();
    }
    controller.printTestingList();
}

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

PS: I've also tried writing to the file manually but that didn't work either! enter code here

PS:我也尝试手动写入文件,但这也不起作用!在此处输入代码

1 个解决方案

#1


0  

Giving it a good look I believe the problem is that the 'home' controller ( which name should start with capital letter ) is null. In order to access your controller you need to do something like this :

给它一个好看的我认为问题是'home'控制器(名称应该以大写字母开头)是null。要访问您的控制器,您需要执行以下操作:

FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/fxml/home.fxml"));

Parent root = loader.load();
controller = loader.getController();

#1


0  

Giving it a good look I believe the problem is that the 'home' controller ( which name should start with capital letter ) is null. In order to access your controller you need to do something like this :

给它一个好看的我认为问题是'home'控制器(名称应该以大写字母开头)是null。要访问您的控制器,您需要执行以下操作:

FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/fxml/home.fxml"));

Parent root = loader.load();
controller = loader.getController();