gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:30:02 25 4
gpt4 key购买 nike

今晚我正在做一项类作业,我已经编写了大部分程序,但是我有一些顽固的代码,无论我如何调整它都无法工作。我可能不太清楚具体对象是如何工作的。

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

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

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

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

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

MenuOperations 中创建 ComboBox 的 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);
}
}

图形用户界面

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;
}

菜单操作:

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;
}

表值:

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
}

以下是完整的错误消息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Operations.getINames(Operations.java:106) at MenuOperations.guiCInventory(MenuOperations.java:109) at GUI$ButtonHandler.actionPerformed(GUI.java:69) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) 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) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) 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) at java.awt.EventDispatchThread.run(Unknown Source)

编辑1:

我已经修复了它,尽管采用了一些偷工减料的方法。

getINames 方法现在写成这样:

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

guiCInventory 中的 ComboBox block 现在如下所示:

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

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

cbItems = new JComboBox(sArray);

现在我只需要让 cInventory 表正常工作就可以了。感谢下面的建议,他们让我达到了现在的水平。

最佳答案

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

您也可以在这里初始化 iNames 看看是否有帮助?

关于java - 线程 "AWT-EventQueue-0"中的异常来自 ComboBox 的 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13025191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com