2014-02-09 38 views
0

我想創建一個刪除按鈕,將刪除一個項目。這裏的目標是當用戶選擇刪除鍵時,刪除當前條目並將所有剩餘項目複製到新的臨時數組中。請注意,我仍然在學習,只是尋求正確方向的幫助,儘管解決方案也是受歡迎的,因爲我也可以向他們學習。我得到的錯誤是相當長的,基於我以前的經驗,我想是與使用空檢查有關,我只是不知道應該在什麼位置提供。爪哇刪除按鈕GUI縮小陣列

以下是錯誤

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
at Bookstore$8.actionPerformed(Bookstore.java:435) 
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) 
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) 
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) 
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) 
at java.awt.Component.processMouseEvent(Component.java:6505) 
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321) 
at java.awt.Component.processEvent(Component.java:6270) 
at java.awt.Container.processEvent(Container.java:2229) 
at java.awt.Component.dispatchEventImpl(Component.java:4861) 
at java.awt.Container.dispatchEventImpl(Container.java:2287) 
at java.awt.Component.dispatchEvent(Component.java:4687) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) 
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) 
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) 
at java.awt.Container.dispatchEventImpl(Container.java:2273) 
at java.awt.Window.dispatchEventImpl(Window.java:2719) 
at java.awt.Component.dispatchEvent(Component.java:4687) 
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735) 
at java.awt.EventQueue.access$200(EventQueue.java:103) 
at java.awt.EventQueue$3.run(EventQueue.java:694) 
at java.awt.EventQueue$3.run(EventQueue.java:692) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) 
at java.awt.EventQueue$4.run(EventQueue.java:708) 
at java.awt.EventQueue$4.run(EventQueue.java:706) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 

這裏是按鈕

JButton deleteButton = new JButton("Delete"); 
    buttonPanel.add(deleteButton); 
    deleteButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent p) 
     { 

      //#1 
      Book[] tempBook = new Book[inventoryBook.length - 1]; 

      //#2 
      Book itemDelete = inventoryBook[bookIndex]; 

      int j = 0; 
      for (int i = 0; i < inventoryBook.length; i++) 
      { 
       if (inventoryBook[i].getISBN() != itemDelete.getISBN()) 
       { 
        tempBook[j] = inventoryBook[i]; 
        j++; 
       } 

      } 
      sortArray(tempBook); 
      inventoryBook = tempBook; 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
     } 
    }); 

請知道,當由用戶選擇的刪除按鈕只會出現此錯誤代碼。沒有編譯錯誤。

下面我已經包含了編譯或查看其他所有代碼的完整代碼。

import java.util.Arrays; 
import java.text.NumberFormat; 
import java.util.Locale; 
import java.text.DecimalFormat; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

// Begin class Book 
class Book 
{ 
private String isbn; 
private String title; 
private String authorName; 
private int yearPublished; 
private String publisherName; 
private double price; 

NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US); 

public Book (String isbn, String title, String authorName, int yearPublished, String publisherName, double price) 
{ 
    this.isbn = isbn; 
    this.title = title; 
    this.authorName = authorName; 
    this.yearPublished = yearPublished; 
    this.publisherName = publisherName; 
    this.price = price; 
} 


/////////////////////////////////////////////// 
public void setISBN (String ISBN) //set ISBN 
{ 
    this.isbn = ISBN; 
} 
public String getISBN() //get ISBN 
{ 
    return isbn; 
} 
////////////////////////////////////////////// 
public void setTitle (String Title) //set Title 
{ 
    this.title = Title; 
} 
public String getTitle() //get Title 
{ 
    return title; 
} 
/////////////////////////////////////////////// 
public void setAuthorName (String AuthorName) //set AuthorName 
{ 
    this.authorName = AuthorName; 
} 
public String getAuthorName() //get AuthorName 
{ 
    return authorName; 
} 
/////////////////////////////////////////////// 
public void setYearPublished (int YearPublished)//set YearPublished 
{ 
    this.yearPublished = YearPublished; 
} 
public int getYearPublished() //get YearPublished 
{ 
    return yearPublished; 
} 
/////////////////////////////////////////////// 
public void setPublisherName (String PublisherName) 
{ 
    this.publisherName = PublisherName; 
} 
public String getPublisherName() 
{ 
    return publisherName; 
} 
/////////////////////////////////////////////// 
public void setPrice (double Price) 
{ 
    this.price = Price; 
} 
public double getPrice() 
{ 
    return price; 
} 


//toString method 
public String toString() 
{ 
    return "ISBN:" + "\t\t\t" + isbn + "\n" + 
      "Title:" + "\t\t\t" + title + "\n" + 
      "Author's Name:" + "\t \t" + authorName + "\n" + 
      "Year Published:" + "\t \t" + yearPublished + "\n" + 
      "Publisher's Name:" + "\t\t" + publisherName + "\n" + 
      "Price" + "\t\t\t" + usCurrency.format(price) + "\n"; 
} 
} // end class Book 


//Begin class EBook 
class EBook extends Book 
{ 
private String webSite; 


// constructor 
public EBook (String isbn, String title, String authorName, int yearPublished, String publisherName, double price, String webSite) 
{ 
    super(isbn, title, authorName, yearPublished, publisherName, price); 
    setWebsite(webSite); 
} 

//accessor methods 
public void setWebsite(String webSite) 
{ 
    this.webSite = webSite; 
} 
public String getWebsite() 
{ 
    return webSite; 
} 


public double discount() 
{ 
    return (super.getPrice()) * .10; // EBook discount of 10% 
} 

public String toString() 
{ 
    return super.toString() + "Website:" + "\t\t\t" + webSite + "\n" + 
        "EBook Discount:" + "\t\t" + usCurrency.format(discount()) + "\n"; 
} 

} //end EBook class 



public class Bookstore 
{ 
private static Book inventoryBook[] = new Book[5]; 
private static NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US); 
static int bookIndex = 0; 
private static Book [] newBookInventory = new Book [inventoryBook.length + 1]; 

public static JTextArea prepareDisplay (Book myBook, JTextArea myTextArea) 
{ 
    myTextArea.setText(""); 

    myTextArea.append(myBook.toString()); 

    return myTextArea; 
} 

public static Book [] sortArray(Book[] books) 
{ 
    // Step1 
    String[] titles = new String[books.length]; 

    // Step2 
    Book[] sortedBooks = new Book [books.length]; 

    // Step3 
    for (int i = 0; i < books.length; i++) 
    { 
     titles[i] = books[i].getTitle(); 
    } 

    // Step4 
    Arrays.sort(titles, String.CASE_INSENSITIVE_ORDER); 

    // Step5 
    for (int i = 0; i < books.length; i++) 
    { 
     for (int j = 0; j < titles.length; j++) 
     { 
      if (books[i].getTitle().equalsIgnoreCase(titles[j])) 
      { 
       sortedBooks[j] = books[i]; 
       break; 
      } 
     } 
    } 

    return sortedBooks; 
} 

public static double calculateInventoryTotal(Book[] books) 
{ 


    double total = 0; 

    for (int i = 0; i < books.length; i++) 
    { 
     if(books[i]!= null) 
     { 
      total += books[i].getPrice(); 
     } 
    } 
    return total; 
} 



public static void main (String args []) 
{ 




    //initial array of Bookstore before anything is added 
    inventoryBook [0] = new EBook ("0075260012", "David goes to School", "David Shannon", 2010, "Shannon Rock", 11.98, "http://www.tinyurl.qqwert67o9"); 
    inventoryBook [1] = new Book ("7423540089", "No David!", "David Shannon", 2009, "Shannon Rock", 12.99); 
    inventoryBook [2] = new Book ("0743200616", "Simple Abundance", "Sarah Breathnach", 2009, "Scribner", 14.99); 
    inventoryBook [3] = new EBook ("78137521819", "The very hungry caterpillar", "Eric Carle", 2005, "Philomel Books", 13.99, "http://www.tinyurl.fguopt8u90"); 
    inventoryBook [4] = new Book ("9781416987116", "We are going on a bear hunt", "Michael Rosen", 2009, "McElderry", 15.99); 




    for (int i = 0; i < inventoryBook.length; i++) 
    { 
     newBookInventory[i] = inventoryBook[i]; 
    } 

    inventoryBook = newBookInventory; 


    //inventoryBook = sortArray(inventoryBook); 

    final double inventoryTotal = calculateInventoryTotal(newBookInventory); 

    final JTextArea textArea = new JTextArea(30, 30); 
    textArea.setText(""); 
    textArea.setEditable(false); 

    JPanel buttonPanel = new JPanel(); 
    buttonPanel.setLayout(new GridLayout(1,3)); 

    JButton firstButton = new JButton("First"); 
    buttonPanel.add(firstButton); 
    firstButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      bookIndex = 0; 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
      textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal)); 
     } 
    }); 

    JButton previousButton = new JButton("Previous"); 
    buttonPanel.add(previousButton); 
    previousButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      if(bookIndex == 0) 
      { 
       bookIndex = inventoryBook.length - 1; 
      } 
      else 
      { 
       bookIndex = bookIndex - 1; 
      } 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
      textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal)); 
     } 
    }); 

    JButton nextButton = new JButton("Next"); 
    buttonPanel.add(nextButton); 
    nextButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      if(bookIndex == inventoryBook.length - 1) 
      { 
       bookIndex = 0; 
      } 
      else 
      { 
       bookIndex = bookIndex + 1; 
      } 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
      textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal)); 
     } 
    }); 

    JButton lastButton = new JButton("Last"); 
    buttonPanel.add(lastButton); 
    lastButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      bookIndex = (inventoryBook.length - 1); 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
      textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal)); 
     } 
    }); 


    JButton searchButton = new JButton("Search"); 
    buttonPanel.add(searchButton); 
    searchButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      boolean matchFound = false; 
      String searchCriteria = JOptionPane.showInputDialog("Enter Book Title"); 

      for (int i = 0; i < inventoryBook.length; i++) 
      { 
       if (inventoryBook[i].getTitle().equalsIgnoreCase(searchCriteria)) 
       { 
        matchFound = true; 
        bookIndex = i; 
        break; 
       } 
      } 

      if (matchFound) 
      { 
       prepareDisplay(inventoryBook[bookIndex], textArea); 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(null, "Book Title " + searchCriteria + " does not exist."); 
      } 
     } 
    }); 

    JButton modifyButton = new JButton("Modify"); 
    buttonPanel.add(modifyButton); 
    modifyButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String title = JOptionPane.showInputDialog(null, "Enter Book Title", inventoryBook[bookIndex].getTitle()); 
      if (title != null) 
      { 
       String isbn = JOptionPane.showInputDialog(null, "Enter ISBN", inventoryBook[bookIndex].getISBN()); 
       if (isbn != null) 
       { 
        String authorName = JOptionPane.showInputDialog(null, "Enter Author's Name", inventoryBook[bookIndex].getAuthorName()); 
        if (authorName != null) 
        { 
         String yearPublished = JOptionPane.showInputDialog(null, "Enter Year Published", inventoryBook[bookIndex].getYearPublished()); 
         if (yearPublished != null) 
         { 
          String publisherName = JOptionPane.showInputDialog(null, "Enter Publisher Name", inventoryBook[bookIndex].getPublisherName()); 
          if (publisherName != null) 
          { 
           String price = JOptionPane.showInputDialog(null, "Enter Price", inventoryBook[bookIndex].getPrice()); 
           if (price != null) 
           { 
            inventoryBook[bookIndex].setTitle(title); 
            inventoryBook[bookIndex].setISBN(isbn); 
            inventoryBook[bookIndex].setAuthorName(authorName); 
            inventoryBook[bookIndex].setYearPublished(Integer.parseInt(yearPublished)); 
            inventoryBook[bookIndex].setPublisherName(publisherName); 
            inventoryBook[bookIndex].setPrice(Double.parseDouble(price)); 

            prepareDisplay(inventoryBook[bookIndex], textArea); 
           } 
          } 
         } 
        } 
       } 
      } 
     } 
    }); 


    JButton addButton = new JButton("Add"); 
    buttonPanel.add(addButton); 
    addButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String isbn = JOptionPane.showInputDialog(null, "Enter ISBN"); 
      if (isbn != null) 
      { 
       String title = JOptionPane.showInputDialog(null, "Enter Title"); 
       if (title != null) 
       { 
        String authorName = JOptionPane.showInputDialog(null, "Enter Author's Name"); 
        if (authorName != null) 
        { 
         String yearPublished = JOptionPane.showInputDialog(null, "Enter Year Published"); 
         if (yearPublished != null) 
         { 
          String publisherName = JOptionPane.showInputDialog(null, "Enter Publisher Name"); 
          if (publisherName != null) 
          { 
           String price = JOptionPane.showInputDialog(null, "Enter Price"); 
           if (price != null) 
           { 


            Book newBook = new Book (isbn, title, authorName, (Integer.parseInt(yearPublished)), publisherName,(Double.parseDouble(price))); 
            inventoryBook[newBookInventory.length - 1] = newBook; 
            prepareDisplay(inventoryBook[bookIndex], textArea); 
           } 
          } 
         } 
        } 
       } 
      } 
     } 
    }); 

    JButton deleteButton = new JButton("Delete"); 
    buttonPanel.add(deleteButton); 
    deleteButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent p) 
     { 

      //#1 
      Book[] tempBook = new Book[inventoryBook.length - 1]; 

      //#2 
      Book itemDelete = inventoryBook[bookIndex]; 

      int j = 0; 
      for (int i = 0; i < inventoryBook.length; i++) 
      { 

       if(inventoryBook[i].getISBN() != itemDelete.getISBN()) 
       { 
        tempBook[j] = inventoryBook[i]; 
        j++; 
       } 

      } 
      sortArray(tempBook); 
      inventoryBook = tempBook; 
      prepareDisplay(inventoryBook[bookIndex], textArea); 
     } 
    }); 





    JLabel logoLabel = new JLabel (new ImageIcon("GoblinBooks.jpg")); 
    JPanel logoPanel = new JPanel(); 
    logoPanel.add(logoLabel); 

    JPanel centerPanel = new JPanel(); 
    centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS)); 
    centerPanel.add(prepareDisplay(inventoryBook[bookIndex], textArea)); 




    //for (int i = 0; i < inventoryBook.length; i++) 
    //{ 
    // textArea.append(inventoryBook[i] + "\n"); 
    //} 



    textArea.append("Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal)); 

    JFrame frame = new JFrame(); 
    frame.setLayout(new BorderLayout()); 
    frame.add(logoPanel, BorderLayout.NORTH); 
    frame.add(buttonPanel, BorderLayout.SOUTH); 
    frame.add(centerPanel, BorderLayout.CENTER); 
    frame.getContentPane().add(new JScrollPane(textArea)); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.pack(); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 
} // end class Bookstore 
+2

哪一行是435行? 'inventoryBook'從哪裏來?是否初始化? –

+0

在你調用inventoryBook.length之前'inventoryBook'已經初始化了嗎?如果不是,那麼你會得到一個'NullPointerException'。另一個檢查null是否爲'bookIndex'的變量。 – dic19

+0

我附上了完整的代碼。 InventoryBook已初始化。 – CoShark

回答

0

這可能是同樣的問題你previous question,一個或多個數組中的元素是null

您可以聲明數組作爲...

private static Book inventoryBook[] = new Book[5]; 
private static Book [] newBookInventory = new Book [inventoryBook.length + 1]; 

然後複製內容如果inventoryBooknewBookInventory,一次一個元素...

for (int i = 0; i < inventoryBook.length; i++) 
{ 
    newBookInventory[i] = inventoryBook[i]; 
} 

inventoryBook = newBookInventory; 

這意味着inventoryBooknewBookInventory都在陣列末尾有一個單一的null元素。

然後,您可以遍歷inventoryBook,訪問每個元素的getISBN方法,沒有檢查,看看是否該元素是null

int j = 0; 
for (int i = 0; i < inventoryBook.length; i++) 
{ 
    if (inventoryBook[i] != null) { 
     if (inventoryBook[i].getISBN() != itemDelete.getISBN()) 
     { 
      tempBook[j] = inventoryBook[i]; 
      j++; 
     } 
    } 
} 

它甚至可能是值得檢查itemDelete,以確保它不是null,但我沒有讀取那麼多的代碼