线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException来自ComboBox

时间:2012-10-23 07:06:51

标签: java swing events nullpointerexception awt

我今晚正在进行课堂作业并且我已经编写了大部分程序但是我有一些固执的代码,无论我如何调整它都无法工作。我可能没有完全理解特定对象的工作原理。

所以发生的事情是我有一个我正在迭代的对象的ArrayList,从中获取一个特定的变量,并保存到一个新的ArrayList中,因为接收对象必须能够根据需要进行更改。

但是当我尝试返回第二个ArrayList时Eclipse告诉我类型不对。我尝试使用它的建议

return (String[]) iNames.toArray();

但是这会导致标题中提到的错误。我也尝试将其作为对象数组传回,但是在创建组合框时也会发生同样的事情。

这是我的代码,你想看的是以下方法:

创建ComboBox的MenuOperations中的guiCInventory 操作中的Object [] getINames()

您可能还想查看addSItem以了解我如何创建TableValues的ArrayList,我将从中提取信息以尝试填充ComboBox。

prg421_w2_IA:

import javax.swing.JFrame;

public class prg421_w2_IA
{
    public static void main(String[] args)
{
    GUI mMenu = new GUI();

    //mMenu.setBounds(100, 100, 537, 223);
    //mMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //mMenu.setVisible(true);
}
}

GUI

import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class GUI extends JFrame
{   
public GUI()
{       
    setBounds(100, 100, 537, 223);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    mMenu = this;       
    setVisible(true);

    lblTitle = new JLabel("Retail Operations Application V1.0");
    lblTitle.setBounds(10, 0, 169, 14);
    add(lblTitle);

    btnAIS = new JButton("Add Item to Store",null);
    btnAIS.setBounds(392, 31, 119, 23);
    add(btnAIS);

    btnAIC = new JButton("Add Item to Customer Cart",null);
    btnAIC.setBounds(348, 65, 163, 23);
    mMenu.getContentPane().add(btnAIC);

    btnSCC = new JButton("Show Customer Cart",null);
    btnSCC.setBounds(380, 99, 131, 23);
    mMenu.getContentPane().add(btnSCC);

    btnEProgram = new JButton("Exit Program",null);
    btnEProgram.setBounds(418, 133, 93, 23);
    mMenu.getContentPane().add(btnEProgram);

    sp = new JScrollPane();
        sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    sp.setBounds(21, 36, 317, 127);
    mMenu.getContentPane().add(sp);

    txtrInstructions = new JTextArea();
    sp.setViewportView(txtrInstructions);
    txtrInstructions.setEditable(false);
    txtrInstructions.setText("Welcome to the Retail Operations Application.  For instructions on how to use the program continue reading.\r\n\r\nImportant Information:\r\nIn order to use this application in this version you must input the items contained in the store inventory before you can use the other functions of the program.\r\n\r\nAdd Item to Store:\r\nPressing this button opens the store inventory editor where you can create new items and edit existing ones.  Using this twice will overwrite the previous store inventory created.\r\n\r\nAdd Item to Customer Cart:\r\nPressing this button opens the dialog to add an item to a customer's shopping cart.  Using this feature twice will overwright previous customer cart.\r\n\r\nShow Customer Cart:\r\nPressing this button will display a list of the items currently in the customer's shopping cart and allow for calculation of the total cost of the customer's purchase.\r\n\r\nExit Program:\r\nOnce done, press this button to close the program.");
    txtrInstructions.setRows(10);
    txtrInstructions.setWrapStyleWord(true);
    txtrInstructions.setLineWrap(true);

    ButtonHandler handler = new ButtonHandler();

    btnAIS.addActionListener(handler);
    btnAIC.addActionListener(handler);
    btnSCC.addActionListener(handler);
    btnEProgram.addActionListener(handler);
}

//Creates inner-class which detects events as they are sent and enacts the proper methods associated with those events.
class ButtonHandler implements ActionListener
{
    public void actionPerformed(java.awt.event.ActionEvent event)
    {
        if (event.getSource() == btnAIS)
        {
            mOps.guiSInventory();
        }

        else if (event.getSource() == btnAIC)
        {
            mOps.guiCInventory();
        }

        else if (event.getSource() == btnSCC)
        {
            mOps.guiCCheckout();
        }

        else if (event.getSource() == btnEProgram)
        {
            mMenu.dispose();
        }

        else
        {
            JOptionPane.showMessageDialog(null,"An error has occured: Message, " + event.getActionCommand() + ", cannot be resolved.", "ERROR CODE 8",JOptionPane.ERROR_MESSAGE);
        }           
    }
}   

//Global References
MenuOperations mOps = new MenuOperations();
JLabel lblTitle; 
JScrollPane sp;

//Main Menu GUI References
JFrame mMenu;
JButton btnAIS;
JButton btnAIC;
JButton btnSCC;
JButton btnEProgram;
JTextArea txtrInstructions; 
}

MenuOperations:

import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;


public class MenuOperations extends JFrame
{

public MenuOperations()
{

}

public void guiSInventory()
{       
    setBounds(100, 100, 537, 390);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    sInv = this;        
    setVisible(true);

    lblTitle = new JLabel("Store Inventory Editor");
    lblTitle.setBounds(10, 0, 169, 14);
    sInv.getContentPane().add(lblTitle);

    sp = new JScrollPane();
    sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    sp.setBounds(10, 161, 501, 180);
    sInv.getContentPane().add(sp);

    sInventory = new JTable();
    tSModel = new DefaultTableModel();
    sInventory.setModel(tSModel);
    tSModel.setColumnIdentifiers(new String[] {"Item Name", "Department", "Item Price", "Item Sale Price"});

    sInventory.getColumnModel().getColumn(0).setPreferredWidth(163);
    sInventory.getColumnModel().getColumn(1).setPreferredWidth(118);
    sInventory.getColumnModel().getColumn(3).setPreferredWidth(95);
    sp.setViewportView(sInventory);

    txtIName = new JTextField();
    txtIName.setText("Item Name");
    txtIName.setBounds(10, 39, 109, 20);
    sInv.getContentPane().add(txtIName);
    txtIName.setColumns(10);

    cbDept = new JComboBox(sDept);
    cbDept.setToolTipText("Choose a Department");
    cbDept.setBounds(157, 39, 133, 20);
    sInv.getContentPane().add(cbDept);

    txtIPrice = new JTextField();
    txtIPrice.setText("Item Price");
    txtIPrice.setBounds(315, 39, 86, 20);
    sInv.getContentPane().add(txtIPrice);
    txtIPrice.setColumns(10);

    txtISPrice = new JTextField();
    txtISPrice.setText("Item Sale Price");
    txtISPrice.setBounds(425, 39, 86, 20);
    sInv.getContentPane().add(txtISPrice);
    txtISPrice.setColumns(10);

    btnAISI = new JButton("Add Item to Inventory",null);
    btnAISI.setBounds(64, 81, 141, 23);
    sInv.getContentPane().add(btnAISI);

    btnExit = new JButton("Exit",null);
    btnExit.setBounds(315, 81, 89, 23);
    sInv.getContentPane().add(btnExit); 

    ButtonHandler handler = new ButtonHandler();

    btnAISI.addActionListener(handler);
    btnExit.addActionListener(handler);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public void guiCInventory()
{
    setBounds(100, 100, 537, 339);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    cInv = this;        
    setVisible(true);

    lblTitle = new JLabel("Store Inventory Editor");
    lblTitle.setBounds(10, 0, 169, 14);
    cInv.getContentPane().add(lblTitle);

    sp = new JScrollPane();
    sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    sp.setBounds(10, 161, 501, 180);
    cInv.getContentPane().add(sp);

    cInventory = new JTable();
    tCModel = new DefaultTableModel();
    cInventory.setModel(tSModel);
    tSModel.setColumnIdentifiers(new String[] {"Item Name", "Department", "Item Price", "Item Sale Price"});

    cInventory.getColumnModel().getColumn(0).setPreferredWidth(163);
    cInventory.getColumnModel().getColumn(1).setPreferredWidth(118);
    cInventory.getColumnModel().getColumn(3).setPreferredWidth(95);
    sp.setViewportView(cInventory);

    Object[] oArray = ops.getINames();
    cbItems = new JComboBox(oArray);
    cbItems.setToolTipText("Choose an Item to Add");
    cbItems.setBounds(10, 39, 133, 20);
    cInv.getContentPane().add(cbItems);

    btnAICI = new JButton("Add Item to Inventory",null);
    btnAICI.setBounds(193, 38, 141, 23);
    cInv.getContentPane().add(btnAICI);

    btnExit2 = new JButton("Exit",null);
    btnExit2.setBounds(411, 38, 89, 23);
    cInv.getContentPane().add(btnExit2);    

    ButtonHandler handler = new ButtonHandler();

    btnAICI.addActionListener(handler);
    btnExit2.addActionListener(handler);
}

public void guiCCheckout()
{

    setBounds(100, 100, 537, 334);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(null);

    cCOut = this;       
    setVisible(true);

    lblTitle = new JLabel("Store Inventory Editor");
    lblTitle.setBounds(10, 0, 169, 14);
    cCOut.getContentPane().add(lblTitle);

    sp = new JScrollPane();
    sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    sp.setBounds(10, 161, 501, 180);
    cCOut.getContentPane().add(sp);

    sp.setViewportView(cInventory);     

    btnCBill = new JButton("Calculate Bill",null);
    btnCBill.setBounds(20, 224, 100, 23);
    cCOut.getContentPane().add(btnCBill);

    txtCBill = new JTextField();
    txtCBill.setText("Calculate Bill");
    txtCBill.setBounds(330, 224, 146, 20);
    cCOut.getContentPane().add(txtCBill);
    txtCBill.setColumns(10);

    btnExit3 = new JButton("Exit",null);
    btnExit3.setBounds(183, 262, 89, 23);
    cCOut.getContentPane().add(btnExit3);

    ButtonHandler handler = new ButtonHandler();

    btnCBill.addActionListener(handler);
    btnExit3.addActionListener(handler);
}

//Creates inner-class which detects events as they are sent and enacts the proper methods associated with those events.
    class ButtonHandler implements ActionListener
    {
        public void actionPerformed(java.awt.event.ActionEvent event)
        {
            if (event.getSource() == btnAISI)
            {           
                //Convert string to float
                f1 = new Float(txtIPrice.getText());
                f2 = new Float(txtISPrice.getText());   

                if (cbDept.getSelectedItem().equals("Appliances"))
                {
                    s2 = "Appliances";          
                }

                else if (obj == Electronics)
                {
                    s2 = "Electronics";
                }

                else if (obj == bBath)
                {
                    s2 = "Bed/Bath";
                }

                else if (obj == Furnishings)
                {
                    s2 = "Furnishings";
                }

                else if (obj == mClothing)
                {
                    s2 = "Men's Clothing";
                }

                else if (obj == wClothing)
                {
                    s2 = "Women's Clothing";
                }

                else if (obj == Landscaping)
                {
                    s2 = "Landscaping";
                }

                else if (obj == Pet)
                {
                    s2 = "Pet";
                }

                ops.addSItem(txtIName.getText(), s2, f1, f2, sInventory, tSModel);
            }

            else if (event.getSource() == btnAICI)
            {
                //Obtain department name
                s1 = (String)cbItems.getSelectedItem();

                ops.addCItem(s1, cInventory, tCModel);
            }

            else if (event.getSource() == btnCBill)
            {
                cTotal = ops.cCBill();

                String.format("%.2f", cTotal) ;

                txtCBill.setText(cTotal.toString());
            }

            else if (event.getSource() == btnExit)
            {
                sInv.dispose();
            }

            else if (event.getSource() ==  btnExit2)
            {
                ops.clearINames();
                cInv.dispose();
            }

            else if (event.getSource() == btnExit3)
            {
                cCOut.dispose();
            }

            else
            {
                JOptionPane.showMessageDialog(null,"An error has occured: Message, " + event.getActionCommand() + ", cannot be resolved.", "ERROR CODE 8",JOptionPane.ERROR_MESSAGE);
            }

        }
    }


//Global References
    Operations ops = new Operations();
    JLabel lblTitle; 
    JScrollPane sp;
    JTextField  txtIName;
    static String[] sDept = {"Appliances","Electronics","Bed/Bath","Furnishings","Men's Clothing","Woman's Clothing","Landscaping","Pet"};
    JTextField  txtIPrice;
    JTextField  txtISPrice;

    //Store Inventory GUI References/Variables
    JFrame      sInv;
    JButton btnAISI;
    JButton btnExit;
    JTable      sInventory;
    JComboBox   cbDept;
    DefaultTableModel tSModel;

    //Customer Inventory GUI References/Variables
    JFrame      cInv;
    JButton     btnAICI;
    JButton     btnExit2;
    JTable      cInventory;
    JComboBox   cbItems;
    DefaultTableModel tCModel;

    //Customer Checkout GUI References
    JFrame cCOut;
    JButton btnCBill;
    JTextField txtCBill;
    JButton btnExit3;


    //btnASIS event method Variables
    Float f1,f2,cTotal;
    Object obj,Appliances,Electronics,bBath,Furnishings,mClothing,wClothing,Landscaping,Pet;
    String s1,s2;


}

操作:

import java.util.ArrayList;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class Operations
{
public Operations()
{
    //Create Array Lists
    sItems = new ArrayList<TableValues>();
    cItems = new ArrayList<TableValues>();      
}

public void addSItem(String s1, String s2, float f1, float f2, JTable table, DefaultTableModel model)
{
    for (i = 0;;i++)
    {
        if (table.getRowCount() < 0)
        {
            if (table.getModel().getValueAt(i,0).equals(s1))
            {
                JOptionPane.showMessageDialog(null,"Item already exists!","Program Information",JOptionPane.PLAIN_MESSAGE);
                break;
            }           

            else if (i == table.getRowCount())
            {
                sItems.add(new TableValues(s1, s2, f1, f2));
                updateSTable(table, model);
                break;
            }
        }

        else
        {
            sItems.add(new TableValues(s1, s2, f1, f2));
            updateSTable(table, model);
            break;              
        }
    }
}

public void addCItem(String s1, JTable table, DefaultTableModel model)
{
    for (i = 0; i < table.getRowCount()-1; i++)
    {       
        if (sItems.get(i).getIName().equals(s1))
        {
            s2 = sItems.get(i).getDName();
            f1 = sItems.get(i).getIPrice();
            f2 = sItems.get(i).getISPrice();

            cItems.add(new TableValues(s1, s2, f1, f2));
            updateSTable(table, model);
            break;
        }

        else if (i == table.getRowCount() - 1)
        {
            JOptionPane.showMessageDialog(null,"Item Does Not Exist!","Error Code 1",JOptionPane.PLAIN_MESSAGE);
            break;
        }
    }
}

public void updateSTable(JTable table, DefaultTableModel model)
{
    table.removeAll();

    for (TableValues items : sItems)
    {
        f1 = items.getIPrice();
        f2 = items.getISPrice();

        s1 = "" +f1;
        s2 = "" +f2;            

        model.addRow(new String[] {items.getIName(), items.getDName(), s1, s2});
    }

    table.revalidate();
}

public void updateCTable(JTable table, DefaultTableModel model)
{
    table.removeAll();

    for (TableValues items : cItems)
    {
        model.addRow(new Object[] {items.getIName(), items.getDName(), items.getIPrice(), items.getISPrice()});
    }

    table.revalidate();
}

public Object[] getINames()
{
    for (i = 0; i < sItems.size()-1; i++)
    {
        iNames.add(sItems.get(i).getIName());
    }

    return iNames.toArray();
}

public void clearINames()
{
    iNames.clear();
}

public float cCBill()
{
    cTotal = 0.0f;

    for (i = 0; i < cItems.size() -1; i++)
    {
        cTotal += cItems.get(i).getISPrice();
    }

    return cTotal;
}


//Variables
public ArrayList<TableValues> sItems; //Store Items
public ArrayList<TableValues> cItems; //Customer Items
public ArrayList<String>      iNames; //Item Names for combobox
String s1,s2;
float f1,f2,cTotal;
int i;
}

TableValues:

public class TableValues
{
public TableValues(String name, String depart, float price1, float price2)
{
    tvIName = name;
    tvDepartment = depart;
    tvIPrice = price1;
    tvISPrice = price2;
}

public String getIName()
{
    return tvIName;
}

public String getDName()
{
    return tvDepartment;
}

public float getIPrice()
{
    return tvIPrice;
}

public float getISPrice()
{
    return tvISPrice;
}

//Variables
public String    tvIName; //Item name
public String    tvDepartment; //Department name
public float         tvIPrice; //Item price
public float         tvISPrice; //Item sale price
}

以下是完整的错误消息:

  

线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException       在Operations.getINames(Operations.java:106)       在MenuOperations.guiCInventory(MenuOperations.java:109)       在GUI $ ButtonHandler.actionPerformed(GUI.java:69)       在javax.swing.AbstractButton.fireActionPerformed(未知来源)       at javax.swing.AbstractButton $ Handler.actionPerformed(Unknown Source)       在javax.swing.DefaultButtonModel.fireActionPerformed(未知来源)       在javax.swing.DefaultButtonModel.setPressed(未知来源)       在javax.swing.plaf.basic.BasicButtonListener.mouseReleased(未知来源)       at java.awt.Component.processMouseEvent(Unknown Source)       在javax.swing.JComponent.processMouseEvent(未知来源)       at java.awt.Component.processEvent(Unknown Source)       at java.awt.Container.processEvent(Unknown Source)       at java.awt.Component.dispatchEventImpl(Unknown Source)       at java.awt.Container.dispatchEventImpl(Unknown Source)       at java.awt.Component.dispatchEvent(Unknown Source)       at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)       at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)       at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)       at java.awt.Container.dispatchEventImpl(Unknown Source)       at java.awt.Window.dispatchEventImpl(Unknown Source)       at java.awt.Component.dispatchEvent(Unknown Source)       at java.awt.EventQueue.dispatchEventImpl(Unknown Source)       在java.awt.EventQueue.access $ 200(未知来源)       在java.awt.EventQueue $ 3.run(未知来源)       在java.awt.EventQueue $ 3.run(未知来源)       at java.security.AccessController.doPrivileged(Native Method)       at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(Unknown Source)       at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(Unknown Source)       在java.awt.EventQueue $ 4.run(未知来源)       在java.awt.EventQueue $ 4.run(未知来源)       at java.security.AccessController.doPrivileged(Native Method)       at java.security.ProtectionDomain $ 1.doIntersectionPrivilege(Unknown Source)       at java.awt.EventQueue.dispatchEvent(Unknown Source)       at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)       at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)       at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)       at java.awt.EventDispatchThread.pumpEvents(Unknown Source)       at java.awt.EventDispatchThread.pumpEvents(Unknown Source)       在java.awt.EventDispatchThread.run(未知来源)

编辑1:

我已经修好了它,虽然它是一种简单的操纵方法。

getINames方法现在写成:

public String getIName(int i)
{
    return sItems.get(i).tvIName;
}

guiCInventory中的ComboBox块现在是这样的:

String[] sArray = new String[ops.getSISize()];

    for (int i = 0; i < ops.getSISize(); i++)
    {
        sArray[i] = ops.getIName(i);
    }

    cbItems = new JComboBox(sArray);

现在我必须让cInventory表工作,我应该完成。感谢下面的建议,他们让我明白我的意思。

3 个答案:

答案 0 :(得分:1)

public Operations()
{
    //Create Array Lists
    sItems = new ArrayList<TableValues>();
    cItems = new ArrayList<TableValues>();      
}

你能在这里初始化iNames,看看它是否有帮助?

答案 1 :(得分:1)

我认为您尚未初始化声明为(iNames

public ArrayList<String> iNames;

您没有实例化您在其上直接调用iNames的{​​{1}}。尝试添加行

正如我在下面添加的add方法中的

iNames = new ArrayList<String>();

getINames()

答案 2 :(得分:0)

请更新您的构造函数,如:
public Operations() { //Create Array Lists sItems = new ArrayList(); cItems = new ArrayList();
iNames = new ArrayList() ; }