Hello Again,

I am in need of some help getting my GUI to display the inventory values. The code runs and compiles successfully, but it does not display anything. I am new to this and could use some help. Thanks!

package inventory;
import java.text.DecimalFormat;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
 *
 * @author Mel
 */

class Pizza {
    // Private variables
    String name;
    private int quantity;
    private double price;
    private int productNumber;
    String textArea;

    // Default constructor uses other constructor to set the
    // default state of the object.

    public Pizza() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor that user can specify a name, quantity, and price for items.
    public Pizza(int number, String itemname, int quantityOnHand, double itemprice) {

        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }

    public void setNumber(int number){
       number = productNumber;
    }
    // Public mutators (changes state of the object)
    public void setName(String itemname) {
        name = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set price of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            price = itemPrice;
        }
        else { price = 0.00; }
    }

    // Get products number
    public int getProductNumber(){
        return productNumber;
    }
    // Get the product's name
    public String getName() {
        return name;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return price;
    }

    // Calculate the value of stock on this particular item.
    public double getItemValue() {
        return (price * (double)quantity);
    }
    public double getRestockFee(){
        return (getItemValue() * 0.05);
    }
 // String representation of the product
    public String toString() {
        return name + " - " + price;
    }



}
public class Inventory {

    // Setup an array of Products (set it to hold 30 items)
    int inventorySize = 30;
    private Pizza items[] = new Pizza[inventorySize];

    // Set the formatter to format values into currency form.
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    // Adds a product to the array of pizza. Adds to first empty slot found.
    public void addPizza(Pizza item) {
        for (int i = 0; i < inventorySize; i++) {
            if (items[i] == null) {
                items[i] = item;
                 return;
            }
        }
    }

    // Loop through our array of pizza and add up the total value.
    // Go item by item adding the quantity on hand x its price.
    // Add that value to a running total variable.

    public double getTotalInvValue() {
        double sumOfInventory = 0.0;

        // Uses a  for loop which iterates the array of items.
        for (Pizza item : items) {

            if (item != null) {
                sumOfInventory += item.getItemValue();
           }
        }
        return sumOfInventory;
    }

    // Prints the inventory list including name, quantity, price, and total stock value for each item.
    public void printInventory() {
        System.out.println("Printing items in inventory...\n");

        boolean hasItems = false;

        for (Pizza item : items) {
            if (item != null) {
                hasItems = true;
                System.out.println(item.toString() + " Quantity: " + item.getQuantityOnHand() + " Value of Stock: " + formatter.format(item.getItemValue()));
            }
        } 

        // If no items were found, print a message saying the inventory is empty.
        if (!hasItems) { System.out.println("Inventory is empty at the moment.\n"); }
    }
}
// Inherited class PizzaRestock from the base class Pizza


class PizzaRestock extends Pizza {
    // Holds the year the move was made
    private String supplier;



    public PizzaRestock(int productNumber, String itemname, int quantityOnHand, double itemprice, String supplier) {
        // Pass on the values needed for creating the Product class first thing
        super(productNumber, itemname, quantityOnHand, itemprice);
        supplier = "";
    }

      // Get the supplier of this Pizza product
    public String getSupplier() {
        return supplier;
    }

    // Overrides getItemValue() in Pizza class by calling the base class version and
    // adding a 5% restocking fee on top
   @Override
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // Simply gets the base class's value, and figures out the 5% restocking fee only
    public double getRestockFee() {
        return super.getItemValue() * .05;
    }
}

class InventoryTest {

     static DecimalFormat formatter = new DecimalFormat("$##,###.00");

    public static void main(String args[]) {


       Pizza item1 = new Pizza(1234, "Dough", 22, 1.99);
       Pizza item2 = new Pizza(1235, "Sauce", 35, 5.99);
       Pizza item3 = new Pizza(1236, "Cheese", 4, 15.99);
       Pizza item4 = new Pizza(1237, "Pepperoni", 3, 14.99);
       Pizza item5 = new Pizza(1238, "Ham", 2, 16.99);




        // Create an inventory item to store our products
        Inventory myPizza = new Inventory();

        // Let's show there is nothing in the inventory to start.
        myPizza.printInventory();

        // Now lets add the items we declared above.
        myPizza.addPizza(item1);
        myPizza.addPizza(item2);
        myPizza.addPizza(item3);
        myPizza.addPizza(item4);
        myPizza.addPizza(item5);

        // Print out the inventory
        myPizza.printInventory();
         // (after formatted using DecimalFormat class into dollars and cents)
        // Print the total value of the inventory
          System.out.println("\nTotal value of inventory is: " + formatter.format(myPizza.getTotalInvValue()));String[] pizza = {"Dough","Sauce","Cheese","Pepperoni","Ham"};
        PizzaGUI gui = new PizzaGUI();
        gui.setVisible(true);
          Arrays.sort(pizza);


         System.out.println("The sorted String array is:");
       for (String name : pizza) {
         System.out.println("Name = " + name); 
         }
    }
}
class PizzaGUI extends JFrame {
    static int max = 5;
    static final Pizza[]Pizza = new Pizza[max];
    int counter;
    /**
     * Creates new form PizzaGUI
     */
    public PizzaGUI() {
        super();
        this.counter = - 1;
        JFrame gui = new JFrame();

        initComponents();
        Pizza[0] = new Pizza(1234,"Dough",22,1.99);
        Pizza[1] = new Pizza(1235, "Sauce", 35, 5.99);
        Pizza[2] = new Pizza(1236, "Cheese", 4, 15.99);
        Pizza[3] = new Pizza(1237, "Pepperoni", 3, 14.99);
        Pizza[4] = new Pizza(1238, "Ham", 2, 16.99);

        gui.add(textArea);
    }
     static void textArea() {
        JTextArea textArea = new JTextArea(Pizza[max].textArea);
        textArea.setVisible(true);
}

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        nextButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        titleLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        nextButton.setText("Next");
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        closeButton.setText("Close Program");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }

            private void backButtonActionPerformed(ActionEvent evt) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });

        titleLabel.setText("Inventory Program");

        textArea.setEditable(false);
        textArea.setColumns(20);
        textArea.setRows(5);
        jScrollPane1.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(backButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
                                .addComponent(closeButton))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(titleLabel)))
                        .addGap(85, 85, 85)
                        .addComponent(nextButton)))
                .addContainerGap()));
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addGap(9, 9, 9)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nextButton)
                    .addComponent(closeButton)
                    .addComponent(backButton))
                .addContainerGap()) );

        pack();
    }// </editor-fold>                       

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        System.exit(0);
    }                                          

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if (counter < 4) {
            counter = counter + 1;
        }else {
            counter = 0;
        }

     textArea.setText(Pizza[counter].getProductNumber() + "");
     textArea.setText(Pizza[counter].getName() + "");
     textArea.setText(Pizza[counter].getPrice() + "");
     textArea.setText(Pizza[counter].getQuantityOnHand() + "");
     textArea.setText(Pizza[counter].getRestockFee() + "");
     textArea.setText(Pizza[counter].getItemValue() + ""); 


    }                                         



    /**
     * @param args the command line arguments
     */
    public void main(String args[]) {


        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PizzaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PizzaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PizzaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PizzaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                new PizzaGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    

    private javax.swing.JButton backButton;
    private javax.swing.JButton closeButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton nextButton;
    private javax.swing.JTextArea textArea;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration                  
}

Recommended Answers

All 21 Replies

without knowing which value should be where and when ... no, we can't.
so far, almost all I see is netbeans generated.

first learn the basic logic, then go for UI programming (and recommended, without the NetBeans wysiwyg)

a 'for instance' out of your code.

textArea.setText(Pizza[counter].getProductNumber() + "");
textArea.setText(Pizza[counter].getName() + "");
textArea.setText(Pizza[counter].getPrice() + "");
textArea.setText(Pizza[counter].getQuantityOnHand() + "");
textArea.setText(Pizza[counter].getRestockFee() + "");
textArea.setText(Pizza[counter].getItemValue() + ""); 

this is actually the same as:

textArea.setText(Pizza[counter].getItemValue() + ""); 

for the simple reason that you overwrite the previous data, and that process goes so fast, the human eye won't see it (unless of course you managed to find a computer using a processor from 1542)

I am just trying to get the inventory to show up in the GUI. Also I am confused as to what you mean about the code being the same as the textArea.setText(Pizza[counter].getItemValue() + ""). What do you mean? Also I am obviously in a crappy school for online programming and do not have much to go on. I appreciate all the help.

each time, you use setText.
setText means "throw away the value now in that component, and replace it with this one".

you 'll need to append the data, instead of setting it.take a look at this

Thank you. One of my biggest problems is knowing where to add the code. Can you point me in the right direction? Also will this help the test show up period because currently the text area is blank when the program runs?.

I already literally told you where you have to change your code.
did you write this code yourself ? it seems to me that it would be impossible to write code like this, and not being able to follow the hints I've given so far.

I got help from a friend that only knows a little bit and some is NetBeans generated.

let me get this straight:
you don't really know Java, neither does the friend who helps you creating applications?

you're going at it the wrong way. first learn the basics of the language, then, learn how to write basic code. see what it does, try and understand why it does what it does. if you think you don't need that, or feel that it goes to slow to advance: if you hadn't skipped this, you would have been able to solve your problem after my first post.

netbeans might be able to create nice looking GUI's, but the downside is: dragging and dropping is as far away from writing (not to mention understanding) code yourself, and, if you want to change the UI later on, it had better not be a professional application, if it is, watch the regression bugs taking over half your workload.
even worse, you might have to go to work for an employer that prohibits the use of netbeans. there's (almost) nothing as sad as a 'senior developer with minimal 5 years experience in Swing development' that has to develop a simple Swing gui and can't do it, because he isn't allowed to use netbeans.

Well the main problem is that I am learning to use the IDE at the same time as learning the language. I had to do the same thing with C++ and Visual Studio. Do you think it is better to use a different IDE? I understand the basics a little, but I believe it is because it is an online class. I have even tried reaching out to fellow classmates, but it seems that none of them want to talk. I feel like I am in the class alone and I do need help other than reading the books. I am more of a visual learner trying to learn from vague books. I am sorry to waste your time. I just need someone who can explain to me when I make a mistake, but even the teacher gives me vague feedback. I am lost and I really need to pass this class. :(

OK
stultuske has given you excellent advice, but all you need to do now is to use tha append method instead of the setText method so that your strings are appended into the text area, not overwritten.

Thank you :)

learning to use the ide while learning the language? that's about the worst thing you can do.
in the end, all you'll actually know, is how to use the ide, not how to write code. the point is, if you actually want to know anything about actual coding, you should be able to write code in notepad, and compile/run using the cmd prompt.
using an ide is good, but not if you don't know what the basic functionalities do 'behind the curtain'

I understand this, but my class is 9 weeks and we are told to use NetBeans and I never used it before this class. I really had no choice in the matter, just trying to the best I can with what they give me. I was interested in pursuing a degree in Software development, but after these programming classes I am not so sure. I am leaning more towards Networking, but I still have to finish this class. I am having a rough time and it seems that it may be the college of choice. I have been thinking about transferring to a different college so that I can actually learn something. I feel like I am just learning how to make these specific programs with vague information and vague feedback. I appreciate all you guys have helped me with so far, so thank you.

Also I did change the code and it is error free, but it still is not displaying anything in the window of the GUI. I understand if you do not want to help me. I honestly an super interested in learning programming, but not like this. Thanks.

well .... if your class is only 9 weeks, don't expect to much value of the "diploma". if you have to use netbeans, you don't really have a choice.
what exactly did you change in the code ?
a good thing to remember: just because it compiles and runs, doesn't mean it's error free. it doesn't do what it's supposed to do, that is as close a definition of an error you can get. but without knowing what you changed, there is very little we can do about it

Well I am hoping that I did it right. This is the part I changed.

     textArea.append(Pizza[counter].getProductNumber() + "");
     textArea.append(Pizza[counter].getName() + "");
     textArea.append(Pizza[counter].getPrice() + "");
     textArea.append(Pizza[counter].getQuantityOnHand() + "");
     textArea.append(Pizza[counter].getRestockFee() + "");
     textArea.append(Pizza[counter].getItemValue() + ""); 

I go to University of Phoenix and these are considered excelerated classes. I take it that is a bad thing.. Which sucks cause I was trying to better myself not just go into debt :(.

I tried going through it, but I've given up, because the code is not only unreadable, it's pretty bad. a few things I noticed:

you have identical arrays in several classes ... why ?
you have all you classes in one file ... do yourself a favour, DON'T do this.
you hide your variables (textArea) and perform actions on local variables with the same name ...
you don't follow naming conventions
you make variables static, while they shouldn't be static
...

this makes your code very hard to read, to follow, let alone maintain and improve, especially for you, since you have little experience in the language.

my advice, start over. think of how it has to be organized
(what objects do I need, what functionalities do I need for that object, ...) and write it as such.

as for the use of these excelerated classes: each semi-respectable course Java that covers ONLY the basics, takes several months. I once had the privilege to follow a full-time Java course (40 hours a week) with only about a month looking at frameworks. the rest of it: basics, basics, and more basics.

to really learn Java (or any other programming language, for that matter) we're talking about years, not a course of weeks.

for online help (tutorial) the best ones (except for the Swing part) remains the official tutorials

My teacher told us it didn't matter if it was all one file. I am sure that most of my problems are because of that. Thanks for the advice and I am sorry it is crap.

Being in one file, vs one file per class, doesn't make a lot of difference IMHO. Personally I wouldn't worry.
Things like having multiple variables with the same name however is very very confusing and unhelpful.

I remember asking if I needed to make a new array to sort mine and was told no. Would you be talking about the array in the GUI part of my code?

you shouldn't have that array in two classes.

I never said that having multiple classes in one file doesn't work, only that it's very difficult to read

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.