0

私は今夜​​クラスの割り当てに取り組んでおり、ほとんどのプログラムを作成していますが、どのように調整しても機能しない頑固なコードがあります。ただし、特定のオブジェクトがどのように機能するかを正確に理解していない可能性があります。

つまり、受信オブジェクトは必要に応じて変更できる必要があるため、反復処理し、特定の変数を取得し、新しいArrayListに保存しているオブジェクトのArrayListがあります。

ただし、2番目のArrayListを返そうとすると、Eclipseはタイプが正しくないことを通知します。私はその提案を使ってみました

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

しかし、それはタイトルに記載されているエラーを引き起こします。また、オブジェクト配列として返すことも試みましたが、コンボボックスの作成時に同じことが起こります。

これが私のコードです。あなたが見たいのは次のメソッドです。

ComboBoxが作成されるMenuOperationsのguiCInventoryOperationsの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.NullPointerExceptionatOperations.getINames(Operations.java:106)at MenuOperations.guiCInventory(MenuOperations.java:109)at GUI $ ButtonHandler.actionPerformed(GUI.java:69) 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) java.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ソース)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(不明なソース)at java.awt.LightweightDispatcher.processMouseEvent(不明なソース)at java.awt.LightweightDispatcher.dispatchEvent(不明なソース)at java.awt.Container.dispatchEventImpl(不明なソース)at java.awt.Window.dispatchEventImpl(不明なソース)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 )java.awt.EventQueue $ 3.run(Unknown Source)atjava.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 。java.awt.EventDispatchThread.run(Unknown Source)のpumpEvents(Unknown Source)

編集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テーブルを機能させる必要があります。これで完了です。以下の提案に感謝します、彼らは私が今いるところに私を連れて行きました。

4

3 に答える 3

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

ここで iNames を初期化して、それが役立つかどうかを確認することもできますか?

于 2012-10-23T07:10:34.587 に答える
1

iNames宣言された as( public ArrayList<String> iNames;)を初期化していないと思います

iNames直接呼び出しているのをインスタンス化していませんadd。行を追加してみてください

iNames = new ArrayList<String>();getINames()以下に追加したように、あなたの方法で:

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

    return iNames.toArray();
}
于 2012-10-23T07:11:07.643 に答える