Inventory program in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #31
    Code:
     
     
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
     
     
     
     
     
    public class Inventory2 extends JFrame implements ActionListener {
     
    //Utility class for displaying the picture
    //If we are going to use a class/method/variable inside that class only, we declare it private in that class
    private class MyPanel extends JPanel {
    ImageIcon image = new ImageIcon("Sample.jpg");
    int width = image.getIconWidth();
    int height = image.getIconHeight();
    long angle = 30;
     
    public MyPanel(){
    super();
    }
    public void paintComponent(Graphics g){
    	super.paintComponent(g);
    	Graphics2D g2d = (Graphics2D)g;
    	g2d.rotate (Math.toRadians(angle), 60+width/2, 60+height/2);
    	g2d.drawImage(image.getImage(), 60, 60, this);
    	g2d.dispose();
    }
    }//end class MyPanel
     
     
    int currentIndex; //Currently displayed Item
    Product[] supplies = new Product[4];
    JLabel name ;
    JLabel number;
    JLabel title;
    JLabel quantity;
    JLabel price;
    JLabel fee;
    JLabel totalValue;
     
    JTextField nameField = new JTextField(20);
    JTextField numberField = new JTextField(20);
    JTextField titleField = new JTextField(20);
    JTextField quantityField = new JTextField(20);
    JTextField priceField = new JTextField(20);
     
     
    JPanel display;
    JPanel displayHolder;
    JPanel panel;
    boolean locked = false; //Notice how I've used this flag to keep the interface clean
    public Inventory2() {
    makeTheDataItems();
     
    setSize(700, 500);
    setTitle("Inventory Program");
    //make the panels
    display = new JPanel();
    JPanel other = new JPanel();
    other.setLayout(new GridLayout(2, 1));
    JPanel picture = new MyPanel();
    JPanel buttons = new JPanel();
    JPanel centerPanel = new JPanel();
    displayHolder = new JPanel();
    display.setLayout(new GridLayout(7, 1));
    //other.setLayout(new GridLayout(1, 1));
     
    //make the labels
    name = new	JLabel("Name :");
    number = new JLabel("Number :");
    title = new JLabel("Title	:");
    quantity = new JLabel("Quantity :");
    price = new JLabel("Price	:");
    fee = new JLabel("Fee :");
    totalValue = new JLabel("Total Value :");
     
    //Use the utility method to make the buttons
    JButton first = makeButton("First");
    JButton next = makeButton("Next");
    JButton previous = makeButton("Previous");
    JButton last = makeButton("Last");
    JButton search = makeButton("Search");
     
     
    //Other buttons
    JButton add = makeButton("Add");
    JButton modify = makeButton("Modify");
    JButton delete = makeButton("Delete");
    JButton save = makeButton("Save");
    JButton exit = makeButton("Exit");
     
    //Add the labels to the display panel
    display.add(name);
    display.add(number);
    display.add(title);
    display.add(quantity);
    display.add(price);
    display.add(fee);
     
    //add the buttons to the buttonPanel
    buttons.add(first);
    buttons.add(previous);
    buttons.add(next);
    buttons.add(last);
    buttons.add(search);
     
     
    //Add the picture panel and display to the centerPanel
    displayHolder.add(display);
    centerPanel.setLayout(new GridLayout(2, 1));
    centerPanel.add(picture);
    centerPanel.add(displayHolder);
    other.add(buttons);
    JPanel forAdd = new JPanel(); // add the other buttons to this panel
    forAdd.add(add);
    forAdd.add(modify);
    forAdd.add(delete);
    forAdd.add(save);
    forAdd.add(exit);
    other.add(forAdd);
     
     
    //Add the panels to the frame
     
    getContentPane().add(centerPanel, "Center");
    getContentPane().add(other, "South");
    this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setVisible(true);
    }
     
    private void makeTheDataItems () {
    Product p1 = new DVD("The one", 001, 200, 100, "The one");
    Product p2 = new DVD("Once upon a time in China V", 002, 500, 10000, "Once upon a time in China V");
    Product p3 = new DVD("Rat Race", 003, 100, 3000, "Rat Race");
    Product p4 = new DVD("The Man in the Iron Mask", 004, 3000, 9000, "The Man in the Iron Mask");
    supplies[0] = p1;
    supplies[1] = p2;
    supplies[2] = p3;
    supplies[3] = p4;
    }
     
    //Utility method for creating and dressing buttons
    private JButton makeButton(String label) {
    JButton button = new JButton(label);
    button.setPreferredSize(new Dimension(100, 25));
    button.setActionCommand(label);
    button.addActionListener(this);
    return button;
    }
     
    private void addItem() {
    panel = new JPanel();
    JPanel add = new JPanel();
     
    add.setLayout(new GridLayout(7, 2));
    JButton addIt = makeButton("Add Item");
     
    JLabel name = new JLabel("Name :");
    JLabel title = new JLabel("Title	:");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price	:");
     
    add.add(name); add.add(nameField);
     
    add.add(title); add.add(titleField);
    add.add(quantity); add.add(quantityField);
    add.add(price); add.add(priceField);
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(addIt);
    panel.add(forAddIt);
     
    displayHolder.remove(display);
    displayHolder.add(panel);
     
    //display = panel;
    this.setVisible(true);
    }
     
     
    public static void main( String args[]) {
    new Inventory2().displayFirst(); //The main method should not have too much code
    } // end main method
     
    public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand(); //This retrieves the command that we set for the button
    //Always compare strings using the .equals method and not using ==
    if(command.equals("First")) {
    if(!locked) {
    	displayFirst();
    }
    }
    else if(command.equals("Next")) {
    if(!locked) {
    	displayNext();
    }
    }
    else if(command.equals("Previous")) {
    if(!locked) {
    	displayPrevious();
    }
    }
    else if(command.equals("Last")) {
    if(!locked) {
    	displayLast();
    }
    }
    else if(command.equals("Exit")) {
    this.dispose();
    System.exit(0);
    }
    else if(command.equals("Add")) {
    if(!locked) {
    	addItem();
    	locked = true;
    }
    }
    else if(command.equals("Add Item")) {
    if(!locked) {
    	addItemToArray();
    	locked = true;
    }
    }
    else if(command.equals("Modify")) {
    if(!locked) {
    	modify();
    	locked = true;
    }
    }
    else if(command.equals("Update")) {
    	 if(!locked) {
    	modifyItemInArray();
    	locked = true;
    }
    }
    else if(command.equals("Delete")) {
    if(!locked) {
    	DVD dvd = (DVD)supplies[currentIndex];
    	 int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete item "+dvd.getItemNumber());
    		 if(confirm == JOptionPane.YES_OPTION) {
    	 removeItemAt(currentIndex);
    	 displayFirst();
    	 }
    }
     
    }
     
    }
    private void modify() {
    DVD dvd = (DVD)supplies[currentIndex];
    panel = new JPanel();
    JPanel add = new JPanel();
    add.setLayout(new GridLayout(7, 2));
    JButton update = makeButton("Update");
    JLabel number = new JLabel("Number :");
    JLabel name = new JLabel("Name :");
    JLabel title = new JLabel("Title	:");
    JLabel quantity = new JLabel("Quantity :");
    JLabel price = new JLabel("Price	:");
    add.add(number);
    numberField.setText(""+dvd.getItemNumber()); numberField.setEditable(false); add.add(numberField);
    add.add(name);
    nameField.setText(dvd.getItemName()); add.add(nameField);
    titleField.setText(dvd.getTitle()); titleField.setEditable(false);
    add.add(title); add.add(titleField);
    add.add(quantity);
    quantityField.setText(""+dvd.getStockQuantity());
    add.add(quantityField);
    add.add(price);
    add.add(priceField); priceField.setText(""+dvd.getItemPrice());
    panel.add(add);
    JPanel forAddIt = new JPanel();
    forAddIt.add(update);
    panel.add(forAddIt);
    displayHolder.remove(display);
    displayHolder.add(panel);
    //display = panel;
    	 this.setVisible(true);
     
    }
     
    private void addItemToArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), titleField.getText());
    //Extend size of array by one first
    Product[] ps = new Product[supplies.length + 1];
    for(int i = 0; i < ps.length-1; i++) {
    ps[i] = supplies[i];
    }
    ps[supplies.length] = p;
    supplies = ps;
    displayHolder.remove(panel);
    displayHolder.add(display);
    displayLast();
    this.setVisible(false);
    this.setVisible(true);
     
    }
     
    //Utility method to ease the typing and reuse code
    //This method reduces the number of lines of our code
    private void displayItemAt(int index) {
     
    DVD product = (DVD)supplies[index];
    name.setText("Item Name: "+ product.getItemName());
    number.setText("Item Number: "+ product.getItemNumber());
    title.setText("Title: "+ product.getTitle());
    quantity.setText("Quantity In Stock: "+ product.getStockQuantity());
    price.setText("Item Price: "+ product.getItemPrice());
    totalValue.setText("Total: " + product.calculateInventoryValue());
    fee.setText("Fee :"+product.calculateRestockFee());
    locked = false;
    this.repaint();
     
     
    this.setVisible(true);
    }
     
    private void modifyItemInArray() {
    Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
    Double.parseDouble(priceField.getText()), titleField.getText());
    supplies[currentIndex] = p;
    displayHolder.remove(panel);
    displayHolder.add(display);
    	displayItemAt(currentIndex);
    this.setVisible(false);
    this.setVisible(true);
     
    }
     
    private void removeItemAt(int index) {
    Product[] temp = new Product[supplies.length-1];
    int counter = 0;
    for(int i = 0; i < supplies.length;i++) {
    if(i == index) { //skip the item to delete
    }
    else {
    	temp[counter++] = supplies[i];
    }
    }
    supplies = temp;
    }
     
    public void displayFirst() {
    displayItemAt(0);
    currentIndex = 0;
    }
     
    public void displayNext() {
    if(currentIndex == supplies.length-1) {
    displayFirst();
    currentIndex = 0;
    }
    else {
    displayItemAt(currentIndex + 1);
    currentIndex++;
     
    }
    }
     
    public void displayPrevious() {
    if(currentIndex == 0) {
    displayLast();
    currentIndex = supplies.length-1;
    }
    else {
    displayItemAt(currentIndex - 1);
    currentIndex--;
    }
    }
     
    public void displayLast() {
    displayItemAt(supplies.length-1);
    currentIndex = supplies.length-1;
    }
     
    }//end class Inventory2
    Only two buttons not yet working now. This should not take a day to complete now. I've deliberately stopped there because I'm sure you have lots of questions to ask at this current stage. You must understand everyline of code there first before we finish it off

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #32
      Code:
       
      
      class Product implements Comparable {
       String name;
       double number;
       long stockQuantity;
       double price;
      
       public Product() {
        name = "";
        number = 0.0;
        stockQuantity = 0L;
        price = 0.0;
      
       }
       public Product(String name, int number, long stockQuantity, double price) {
        this.name = name;
        this.number = number;
        this.stockQuantity = stockQuantity;
        this.price = price;
       }
       public void setItemName(String name) {
        this.name = name;
       }
       public String getItemName() {
        return name;
       }
       public void setItemNumber(double number) {
        this.number = number;
       }
       public double getItemNumber() {
        return number;
       }
       public void setStockQuantity(long quantity) {
        stockQuantity = quantity;
       }
       public long getStockQuantity() {
        return stockQuantity;
       }
       public void setItemPrice(double price) {
        this.price = price;
       }
       public double getItemPrice() {
        return price;
       }
       public double calculateInventoryValue() {
        return getItemPrice() * getStockQuantity();
       }
       public int compareTo (Object o) {
        Product p = (Product)o;
        return name.compareTo(p.getItemName());
       }
       public String toString() {
        return "Name :"+getItemName() + "\nNumber"+number+"\nPrice"+price+"\nQuantity"+stockQuantity + "\nValue :"+calculateInventoryValue();
       }
      
      } 
      
       
      
      class DVD extends Product implements Comparable {
       private String title;
       public DVD() {
        super(); //Call the constructor in Product
        title = ""; //Add the additonal attribute
       }
       public DVD(String name, int number, long stockQuantity, double price, String title) {
        super(name, number, stockQuantity, price); //Call the constructor in Product
        this.title = title; //Add the additonal attribute
       }
       public void setTitle(String title) {
        this.title = title;
       }
       public String getTitle() {
        return title;
       }
       public double calculateInventoryValue() {
        return getItemPrice() * getStockQuantity() + getItemPrice()*getStockQuantity()*0.05;
       }
      
       public double calculateRestockFee() {
        return getItemPrice() * 0.05;
       }
       public int compareTo (Object o) {
        Product p = (Product)o;
        return getItemName().compareTo(p.getItemName());
       }
       public String toString() {
        return "Name :"+getItemName() + "\nNumber"+getItemNumber()+"\nPrice"+getItemPrice()+"\nQuantity"+getStockQuantity() +"\nTitle :"+getTitle()+"\nValue"+calculateInventoryValue();
       }
      }
      The Product and DVD classes remain unchanged

      Comment

      • stevedub
        New Member
        • Jan 2007
        • 40

        #33
        I think I am slowly starting to understand the code, and what it is actually doing. I think my biggest problem is trying to figure out the order in which to present the code. This may take some time to digest, but it looks great, thank you so much.

        Comment

        • ITQUEST
          New Member
          • Feb 2007
          • 11

          #34
          Originally posted by stevedub
          I think I am slowly starting to understand the code, and what it is actually doing. I think my biggest problem is trying to figure out the order in which to present the code. This may take some time to digest, but it looks great, thank you so much.

          Stevedub,
          Looks like I am in the same class you are but only in Week 5. I am completely lost and the teacher is NO help!
          Can you offer any advice for the Wk 5 Checkpoint? It is the Inventory Program Part 1.

          ITQUEST

          Comment

          • ITQUEST
            New Member
            • Feb 2007
            • 11

            #35
            Originally posted by ITQUEST
            Stevedub,
            Looks like I am in the same class you are but only in Week 5. I am completely lost and the teacher is NO help!
            Can you offer any advice for the Wk 5 Checkpoint? It is the Inventory Program Part 1.

            ITQUEST
            Me again...
            I am also wondering how to set up a class. I get how to establish the Java file but the class thing has me confused. What is the difference? I guess I have just been getting by until now, but I can't seem to get it right!
            ITQUEST

            Comment

            • stevedub
              New Member
              • Jan 2007
              • 40

              #36
              Hehe, I feel your pain bro, wait till you get further into the class. Here is the code I have from week 5:
              Code:
              // Product class
              
              
              public class Product {
              
              	private String title;
              	private double item;
              	private double stock;
              	private double price;
              
              	// Constructor to initialize the product information.
              	public Product(String title, double item, double stock,
              			double price) {
              		setTitle(title);
              		setItem(item);
              		setStock(stock);
              		setPrice(price);
              
              	}
              
              	// Method to get the title
              	public String getTitle() {
              		return title;
              	}
              
              	// Method to get the item number
              	public double getItem() {
              		return item;
              	}
              
              	//Method to get the stock
              	public double getStock() {
              		return stock;
              	}
              
              	//Method to get the price
              	public double getPrice() {
              		return price;
              
              
              
              	}
              
              	// Method to set the title name.
              	public void setTitle(String title) {
              		this.title = title;
              	}
              
              	// Method to set the item number.
              	public void setItem(double item) {
              		this.item = item;
              	}
              
              	// Method to set the stock available.
              	public void setStock(double stock) {
              		this.stock = stock;
              	}
              
              	//Method to set the price.
              	public void setPrice(double price) {
              		this.price = price;
              
              	}
              	// Method to compute the value of inventory.
              	public double getInvValue() {
              		return this.stock *this.price;
              	}
              
              }
              
              
              // This is a new class Inventory
              // Inventory program
              // Main application
              
              
              
              public class Inventory
              {
              	public static void main (String args [])
              	{
              
              	System.out.println ("Inventory of DVD Movies:\n");
              
              		String title = "Beerfest";
              		double item = 1;
              		double stock = 15;
              		double price = 22.50;
              		double value;
              
              	Product product = new Product (title, item, stock, price);
              
              	System.out.printf( "%s%18s\n", "DVD Title:", product.getTitle() );
              
              	System.out.printf( "%s%16s\n", "Item #:", product.getItem() );
              
              	System.out.printf( "%s%8s\n", "Number in Stock:" , product.getStock() );
              
              	System.out.printf( "%s%18s\n", "Price:", product.getPrice() );
              
              
              
              	System.out.printf( "%s%9s\n", "Inventory Value:", product.getInvValue() );
              
              	}
              }

              Comment

              • stevedub
                New Member
                • Jan 2007
                • 40

                #37
                Let me know if you have any questions about the code.

                Comment

                • ITQUEST
                  New Member
                  • Feb 2007
                  • 11

                  #38
                  Originally posted by stevedub
                  Let me know if you have any questions about the code.

                  Do you post the first half as your .java and the second as your .class to get it to run? I understand how you have it written. I can read the material and understand it when I see it, but putting the two together is the challenge for me.

                  I have to say that all of the classes so far have been fine, but this one is bad. Do you mind me asking questions along the way or will you leave this forum after you complete the course?

                  ITQUEST

                  Comment

                  • ITQUEST
                    New Member
                    • Feb 2007
                    • 11

                    #39
                    Originally posted by ITQUEST
                    Do you post the first half as your .java and the second as your .class to get it to run? I understand how you have it written. I can read the material and understand it when I see it, but putting the two together is the challenge for me.

                    I have to say that all of the classes so far have been fine, but this one is bad. Do you mind me asking questions along the way or will you leave this forum after you complete the course?

                    ITQUEST
                    I run it and get the following error:

                    NoClassDefFound Error: Product

                    Any suggestions?

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #40
                      Originally posted by ITQUEST
                      I run it and get the following error:

                      NoClassDefFound Error: Product

                      Any suggestions?
                      .java classes are compiled to into .class files. If you have a .java file called Product.java, when you compile it a .class is created for every class in the file Product.java if there are no errors. In this case you are getting this error because there is no class file called Product.class so you must compile the Product class first.

                      Comment

                      • stevedub
                        New Member
                        • Jan 2007
                        • 40

                        #41
                        Yes, you have to put each part of the program in a seperate file and compile them using the name of the class. Make sure to save the program with the .java extension. Also make sure both files are in the same location.

                        As for comming back after this assignment, I will gladly try to help out once I get this final assignment figured out. ro35198x has been such a great help for me, and I would be glad to pass on the knowledge he has shared to me.

                        Should he start a new thread r035198x so we don't get the two projects confused?

                        Comment

                        • stevedub
                          New Member
                          • Jan 2007
                          • 40

                          #42
                          Hey r035198x, for some reason the add feature doesn't seem to be working for me any more, I'm not sure what got changed exactly.

                          Comment

                          • r035198x
                            MVP
                            • Sep 2006
                            • 13225

                            #43
                            Originally posted by stevedub
                            Hey r035198x, for some reason the add feature doesn't seem to be working for me any more, I'm not sure what got changed exactly.
                            Ok I see where the problem is. Just change the addItem part to

                            Code:
                             
                            else if(command.equals("Add Item")) {
                               addItemToArray();
                              }
                            That part does not need to check the lock

                            Comment

                            • stevedub
                              New Member
                              • Jan 2007
                              • 40

                              #44
                              Is this the part I am suppose to change? I don't think I did it right.

                              Code:
                              //Always compare strings using the .equals method and not using ==
                              if(command.equals("First")) {
                              if(!locked) {
                              	displayFirst();
                              }
                              }
                              else if(command.equals("Next")) {
                              if(!locked) {
                              	displayNext();
                              }
                              }
                              else if(command.equals("Previous")) {
                              if(!locked) {
                              	displayPrevious();
                              }
                              }
                              else if(command.equals("Last")) {
                              if(!locked) {
                              	displayLast();
                              }
                              }
                              else if(command.equals("Exit")) {
                              this.dispose();
                              System.exit(0);
                               }
                              
                              }
                              }
                              else if(command.equals("Add Item")) {
                                 addItemToArray();
                                }
                              }
                              }
                              else if(command.equals("Modify")) {
                              if(!locked) {
                              	modify();
                              	locked = true;
                              }
                              }
                              else if(command.equals("Update")) {
                              	 if(!locked) {
                              	modifyItemInArray();
                              	locked = true;
                              }
                              }

                              Comment

                              • r035198x
                                MVP
                                • Sep 2006
                                • 13225

                                #45
                                Originally posted by stevedub
                                Is this the part I am suppose to change? I don't think I did it right.

                                Code:
                                //Always compare strings using the .equals method and not using ==
                                if(command.equals("First")) {
                                if(!locked) {
                                	displayFirst();
                                }
                                }
                                else if(command.equals("Next")) {
                                if(!locked) {
                                	displayNext();
                                }
                                }
                                else if(command.equals("Previous")) {
                                if(!locked) {
                                	displayPrevious();
                                }
                                }
                                else if(command.equals("Last")) {
                                if(!locked) {
                                	displayLast();
                                }
                                }
                                else if(command.equals("Exit")) {
                                this.dispose();
                                System.exit(0);
                                }
                                 
                                }
                                }
                                else if(command.equals("Add Item")) {
                                addItemToArray();
                                }
                                }
                                }
                                else if(command.equals("Modify")) {
                                if(!locked) {
                                	modify();
                                	locked = true;
                                }
                                }
                                else if(command.equals("Update")) {
                                	 if(!locked) {
                                	modifyItemInArray();
                                	locked = true;
                                }
                                }
                                Yes that's the part. Why are you unsure about it?

                                Comment

                                Working...