使用ObservaleList将元素添加到ListView中

时间:2015-12-10 20:48:38

标签: java swing javafx

我遇到了向ObservableList添加数组的问题,使用它将该数组添加到ListView中。编译时,我得到了NullPointerException。当我调用listAllItems()方法时会发生此异常。如果我不使用GUI控件,而不是使用switch-statement并让用户选择该选项,那么在运行时不会发生异常。有人可以帮我弄清楚会发生什么吗?感谢

要求

创建LibraryGUI类 ◦此类应具有Library对象作为其字段之一。在LibraryGUI构造函数中 您将需要调用库构造函数方法来初始化此字段,然后调用它 open()方法从数据文件中读取项目。 ◦使用JList显示库的内容。使用JList的setListData方法 class与Library类的listAllItems方法一起使列表保持当前状态 图书馆内容。

import javax.swing.JOptionPane;
public class MediaItem {
/*Fields*/
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;

/*Default Constructor - Initialize string variables for null and boolean variable for false*/
public  MediaItem()
{
    title = null;
    format = null;
    onLoan = false;
    loanedTo = null;
    dateLoaned = null;
}

/*Parameterized Constructor*/
public MediaItem(String title, String format)
{
    this.title = title;
    this.format = format;
    this.onLoan = false;
}



public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getFormat() {
    return format;
}

public void setFormat(String format) {
    this.format = format;
}

public boolean isOnLoan() {
    return onLoan;
}

public void setOnLoan(boolean onLoan) {
    this.onLoan = onLoan;
}

public String getLoanedTo() {
    return loanedTo;
}

public void setLoanedTo(String loanedTo) {
    this.loanedTo = loanedTo;
}

public String getDateLoaned() {
    return dateLoaned;
}

public void setDateLoaned(String dateLoaned) {
    this.dateLoaned = dateLoaned;
}

/*Mark item on loan*/
  void markOnLoan(String name, String date){      
      if(onLoan == true)
          JOptionPane.showMessageDialog(null,this.title + " is already loaned out to " + this.loanedTo + " on " + this.dateLoaned);
      else {
              onLoan = true;
              loanedTo = name;
              dateLoaned = date;
      }
  }
/*Mark item return*/
      void markReturned(){
          if(onLoan == false)
              JOptionPane.showMessageDialog(null, this.title + " is not currently loaned out");
          onLoan = false; 
      }

}

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javafx.scene.control.TextInputDialog;

public class Library extends MediaItem {
/*Fields*/
private ArrayList<MediaItem> itemsList = new ArrayList<>();




public ArrayList<MediaItem> getItemsList() {
    return itemsList;
}

public void setItemsList(ArrayList<MediaItem> itemsList) {
    this.itemsList = itemsList;
}
public int  displayMenu()
{
    Scanner input = new Scanner(System.in);
    System.out.println("\nMenu Options \n"
                    +"\n1. Add new item\n"
                    +"\n2. Mark an item as on loan\n"
                    +"\n3. List all item\n"
                    +"\n4. Mark an item as returned\n"
                    +"\n5. Quit\n"
                    +"\n\nWhat would you like to do?\n");
    int choices =  input.nextInt();
    while (choices < 1 || choices >5)
    {
        System.out.println("I'm sorry, " + choices + " is invalid option");
        System.out.println("Please choose another option");
        choices = input.nextInt();
    }
    return (choices);
}

public void addNewItem(String title, String format)
{
    MediaItem  item = new MediaItem(); // the object of item
    /*Use the JOptionPane.showInputDialog(null,prompt) to let the user input the title and the format
     * store the title and the format to the strings and pass it to the parameter of addNewItem(String, String) method 
     * title and format will go through the loop if title already exited let the user input another title and format
     * Using the same method JOptionPan.ShowInputDialog and JOptionPane.showMessage()
     */
    boolean matches = false;
    for(int i = 0; i< itemsList.size(); i++){
        if(title.equals(itemsList.get(i).getTitle())){
            String newTitle = JOptionPane.showInputDialog(null, "this " + title + " already exited. Please enter the title again");

            String newFormat = JOptionPane.showInputDialog(null, "Enter the format again");

             item = new MediaItem(newTitle,newFormat);
             itemsList.add(item);
             matches = true;

        }
    }if(!matches){
        item = new MediaItem(title,format);
        itemsList.add(item);
        }


}

public void markItemOnLoan(String title, String name, String date)
{
    boolean matches = false;
    for(int i = 0; i < itemsList.size(); i++)
    {   if (title.equals(itemsList.get(i).getTitle()))
        {
        itemsList.get(i).markOnLoan(name,date);
        matches = true;
        }
    } 
    if (!matches)
    {
        JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
    }

}

public String[] listAllItems()
{
    String[] list = new String[itemsList.size()];
    for (int n = 0; n < itemsList.size(); n++)
    {
        if(itemsList.get(n).isOnLoan() == true)
            list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + " ) loaned to " + itemsList.get(n).getLoanedTo() + " on " + itemsList.get(n).getDateLoaned();

            else
            list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + ")";
            if(list[n] == null){
                String title = "title ";
                String format = "format ";
                String loanTo = "name ";
                String date = "date ";
                list[n] = title + format + loanTo + date;
            }

    }
    return list;

}

public void markItemReturned(String title)
{
    boolean matches = false;
    for( int i = 0; i < itemsList.size(); i++)
    {
        if(title.equals(itemsList.get(i).getTitle()))
        {
            matches = true;
            itemsList.get(i).markReturned();
        }

    }
    if(!matches)
    {
        JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
    }
}
public void deleteItem(String title){
    boolean matches = false;
    for(int i = 0; i < itemsList.size(); i++){
        if(title.equals(itemsList.get(i).getTitle())){
            itemsList.get(i).setTitle(null);
            itemsList.get(i).setFormat(null);
            itemsList.get(i).setDateLoaned(null);
            itemsList.get(i).setLoanedTo(null);
            itemsList.get(i).setOnLoan(false);
        }
    }
    if(!matches)
        JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}

public void openFile(){
    Scanner input = null; 
    try{
         input = new Scanner(new File("library.txt"));
         Scanner dataInput = null;
         MediaItem item = new MediaItem();
         int index = 0;
         String title = " ";
         String format = " ";
         String date = " ";
         String onLoanTo = " ";
         Boolean onLoan = false;
         Boolean checkString= false;
         Boolean checkBoolean = false;
         itemsList = new ArrayList<>();

         while(input.hasNextLine()){
             dataInput = new Scanner(input.nextLine());
             dataInput.useDelimiter("-");
             while(input.hasNext()){
                 Boolean dataBoolean = dataInput.nextBoolean();
                 String dataString = dataInput.next();

                 if(index == 0){
                     item.setTitle(dataString);
                     title = item.getTitle();
                     checkString = true; 
                 }else if(index == 1){
                     item.setFormat(dataString);
                     format = item.getFormat();
                     checkString= true;
                 }else if(index == 2){
                     item.setOnLoan(dataBoolean);
                     checkBoolean = true;
                 }else if(index == 3){
                     item.setLoanedTo(dataString);
                     checkString = true;
                 }else if(index == 4){
                     item.setDateLoaned(dataString);
                     checkString = true;
                 }else {
                    if(checkString == false)
                        throw new Exception("Invalid data " + dataString);
                    if(checkBoolean == false)
                        throw new Exception("Invalid data " + dataBoolean);
                 }
                 index++;
                 itemsList.add(new MediaItem(title,format));
             }
              index = 0;
              title = " ";
              format = " ";
              date = " ";
              onLoan = false;
              onLoanTo = " ";

              checkString= false;
              checkBoolean = false;
         }
     }catch(Exception ex){
         JOptionPane.showMessageDialog(null, ex.getMessage());
     }finally{
         if(input != null){
             try{
                 input.close();
             }catch(NullPointerException ex){
                 JOptionPane.showMessageDialog(null,"Error: File can not be closed");
             }
         }
     }

}
public void saveFile(){

PrintWriter output = null;
    try{
     output = new PrintWriter(new File("library.txt"));
        for(int i = 0; i < itemsList.size(); i++){
             output.println(itemsList.get(i).getTitle() + "-" + itemsList.get(i).getFormat()+ "-" + itemsList.get(i).isOnLoan() + "-" 
                     + itemsList.get(i).getLoanedTo()   + "-" + itemsList.get(i).getDateLoaned());
        }
    }catch(FileNotFoundException e1){
        JOptionPane.showMessageDialog(null,"Could not find the data file. Program is exiting.");
    }catch(IOException e2){
        JOptionPane.showMessageDialog(null, "Something went wrong with writing to the data file.");
    }catch(Exception e3){
        JOptionPane.showMessageDialog(null,"Something went wrong.");
    }
    finally{
        if( output != null){
            try{
            output.close();
            System.exit(0);
            }catch (NullPointerException e4){
                JOptionPane.showMessageDialog(null, "Error: File can not be closed");
            }
        }
    }
}

}

enter code here

import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;

public class LibraryGUI extends Application{
private ListView<String> listView;
private Library library;
private Button btAdd, btCheckIn, btCheckOut, btDelete;

public void LibraryGUI(){
    library = new Library();
    library.openFile();
}

public void start(Stage primaryStage) throws Exception {
    listView = new ListView<>();

    //Add all item in the listAllItem() method to the list view

        String[] list = library.listAllItems();
    int length = library.getItemsList().size();
    for (int i = 0; i < length; i++)
    {
        ObservableList<String> element = FXCollections.observableArrayList( list[i].toString());
        listView.setItems(element);
    }


    listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

    btAdd = new Button("         Add");
    btCheckIn = new Button("     CheckIn ");
    btCheckOut = new Button("  CheckOut ");
    btDelete = new Button("      Delete ");

    FlowPane flowP = new FlowPane();

    listView.setPrefSize(400, 275);

    btAdd.setPrefSize(100, 25);
    btAdd.setAlignment(Pos.BOTTOM_LEFT);
    btCheckIn.setPrefSize(100, 25);
    btCheckIn.setAlignment(Pos.BOTTOM_LEFT);
    btCheckOut.setPrefSize(100, 25);
    btCheckOut.setAlignment(Pos.BOTTOM_LEFT);
    btDelete.setPrefSize(100,25);
    btDelete.setAlignment(Pos.BOTTOM_LEFT);

    flowP.getChildren().addAll(listView,btAdd,btCheckIn,btCheckOut,btDelete);

    Scene scene = new Scene (flowP,400,300);
    primaryStage.setTitle("Calculator");
    primaryStage.setScene(scene);
    primaryStage.show();
}
public static void main(String[] args)  {

    launch(args);
}

}

Switch-Statement的代码

import java.util.Scanner;

public class Code8 {
public static void main(String[] args) {
    MediaItem newItem = new MediaItem();
    Library library = new Library();
    Scanner in = new Scanner(System.in);
    int option = 0;
    while (option != 5)
    {
        option = library.displayMenu();

        switch(option)
        {
        case 1:
            System.out.print("What is the title? ");
            String newTitle = in.nextLine();
            newItem.setTitle(newTitle);

            System.out.println("What is the format? ");
            String newFormat = in.nextLine();
            newItem.setFormat(newFormat);

            library.addNewItem(newTitle, newFormat);
        break;
        case 2:
            System.out.println("Which item (enter the title)? ");
            newTitle = in.nextLine();
            newItem.setTitle(newTitle);


            System.out.println("Who are you loaning it to? ");
            String name = in.nextLine();
            newItem.setLoanedTo(name);

            System.out.println("When did you loan it to them? ");
            String date = in.nextLine();

            library.markItemOnLoan(newTitle, name, date);


                break;
        case 3:
            String[] list = library.listAllItems();
            int length = library.getItemsList().size();
            for (int i = 0; i < length; i++)
            {
                System.out.println(list[i].toString());
            }
            break;
        case 4:
            System.out.println("Which item (enter the title)? ");
            newTitle = in.nextLine();
            newItem.setTitle(newTitle);

            library.markItemReturned(newTitle);
            break;
        case 5:
            System.out.println("Goodbye");
            break;

        }// switch statement

    }//while statement
} //main method

}

0 个答案:

没有答案