8 Replies - 4637 Views - Last Post: 24 February 2012 - 03:10 PM Rate Topic: -----

#1 jgammon1979  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-February 12

Having issues with inventory program part 6 assignment

Posted 16 February 2012 - 06:25 PM

I'm struggling trying to figure out how to complete this assignment. I've created the buttons, just not sure how to make them function to add new info to database, delete it, modify it, or save it. This is the assignment details:

Starting with your last submission (Inventory Program Part 5), - Modify the Inventory Program to include an Add button, a Delete button, and a Modify button on the GUI. These buttons should allow the user to perform the corresponding actions on the item name, the number of units in stock, and the price of each unit.
- Add a Save button to the GUI that saves the inventory to a C:\data\inventory.dat file.
- Use exception handling to create the directory and file if necessary.
- Add a search button to the GUI that allows the user to search for an item in the inventory by the product name. If the product is not found, the GUI should display an appropriate message. If the product is found, the GUI should display the product’s information in the GUI.
- Keep the previous functionality intact from the previous Inventory Assignments.

This is what I have so far from Inventory program part 5:

 
Inventory file:
 
package comparable.Inventory; // packages Inventory class into comparable folder
 import java.awt.Color; // imports java.awt's Colors
 import java.awt.Font; // imports java.awt's Fonts
 import java.awt.Graphics;
 import java.awt.GridLayout; // imports java.awt's GridLayout layout
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.io.FileInputStream;
 import java.io.ObjectInputStream;
 
import javax.swing.JTextField; // imports javax.swing's JTextField
 import java.util.Arrays; // imports java Array utility
 
import javax.swing.Icon;
 import javax.swing.ImageIcon;
 import javax.swing.JButton;
 import javax.swing.JFrame; // imports javax.swing's JFrame
 import javax.swing.JPanel; // imports javax.swing's JPanel
 import javax.swing.JLabel; // imports javax.swing's JLabel
 
public class Inventory // declares class Inventory
 {
 // declares new array of ProductProducer class called product1 with 6 elements
 private static ProductProducer[] product1 = new ProductProducer[6];
 private static int current = 0;
 private static JTextField itemNumber, dvd, producer, units, price, value;
 

// starts execution of Main function
 public static void main(String args[])
 { 
// sets values for element 0
 product1[0] = new ProductProducer("The Darkest Hour", "Chris Gorak",
 25, 10, 12.50);
 
// sets values for element 1
 product1[1] = new ProductProducer("The Smurfs", "Raja Gosnell",
 184, 5, 10.50);
 
// sets values for element 2
 product1[2] = new ProductProducer("Free Runner", "Lawrence Silverstein",
 212, 25, 17.50);
 
// sets values for element 3
 product1[3] = new ProductProducer("Happy Feet 2", "George Miller",
 51, 17, 14.50);
 
// sets values for element 4
 product1[4] = new ProductProducer("Immortals", "Tarsem Singh",
 112, 12, 10.80);
 
// sets values for element 5
 product1[5] = new ProductProducer("In Time", "Andrew Niccol",
 118, 9, 15.50);
 
// Creates Font to be used for JText below
 Font f = new Font("Times New Roman", Font.BOLD, 24);
 
// Creates JTextFields
 itemNumber = new JTextField(10);
 dvd = new JTextField(10);
 producer = new JTextField(10);
 units = new JTextField(10);
 price = new JTextField(10);
 value = new JTextField(10);
 
// sorts array by dvd name
 Arrays.sort(product1);
 
// creates JFrame with title
 JFrame frame = new JFrame( "DVD Inventory Collection" ); 
// sets close operation for JFrame
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
// creates new JPanel fieldPanel
 
// Declares a new JPanel and calls it fieldPanel
 JPanel fieldPanel = new JPanel();
 
// creates GridLayout for fieldPanel JPanel
 fieldPanel.setLayout( new GridLayout(7, 6));
 
// creates ImageIcon for image.png in source folder
 ImageIcon image = new ImageIcon("image.png");
 
// Creates new JLabel and fills it with image.png
 JLabel picture = new JLabel(image); 

// adds picture JLabel to fieldPanel
 fieldPanel.add(picture);
 
// Creates JLabel to display title
 JLabel logoMessage = new JLabel("My Movie Inventory");
 logoMessage.setFont(f); // sets font of logoMessage to f font defined above
 fieldPanel.add(logoMessage); // adds logMessage to fieldPanel
 JLabel blank2 = new JLabel(); // Creates blank JLabel to skip grid
 fieldPanel.add(blank2); // adds blank label to grid
 JLabel blank3 = new JLabel(); // Creates another blank JLabel to skip another grid
 fieldPanel.add(blank3); // adds blank label to grid
 
// creates JLabel to be used as column header for item numbers
 JLabel itemNumberLabel = new JLabel( "Item Number: " ); 
fieldPanel.add(itemNumberLabel); // adds new JLabel to fieldPanel
 fieldPanel.add(itemNumber); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for dvd titles
 JLabel dvdLabel = new JLabel( " Dvd title: " ); 
fieldPanel.add( dvdLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( dvd ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for producers
 JLabel producerLabel = new JLabel( " Producer: " ); 
fieldPanel.add( producerLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( producer ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Units
 JLabel unitsLabel = new JLabel( " Units: " ); 
fieldPanel.add( unitsLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( units ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Prices
 JLabel priceLabel = new JLabel( " Price: " ); 
fieldPanel.add( priceLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( price ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Values
 JLabel valueLabel = new JLabel( " Value: " ); 
fieldPanel.add( valueLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( value ); // adds JTextField to fieldPanel
 

// Declares 4 JButtons and gives them names
 JButton first = new JButton( "First Item" );
 JButton last = new JButton( "Last Item" );
 JButton previous = new JButton( "Previous Item" );
 JButton next = new JButton( "Next Item" );
 JButton add = new JButton( "Add" );
 JButton delete = new JButton( "Delete" );
 JButton modify = new JButton( "Modify" );
 JButton search = new JButton( "Search" );
 JButton save = new JButton( "Save" );
 
// Creates action listener for first JButton
 first.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 current = 0;
 refresh(); // calls refresh method
 }
 }
 );
 
// adds first JButton to fieldPanel
 fieldPanel.add( first );
 
// Creates action listener for last JButton
 last.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 current = (product1.length - 1 );
 refresh(); // calls refresh method
 }
 }
 );
 
// adds last JButton to fieldPanel
 fieldPanel.add( last );
 
// Creates action listener for next JButton
 next.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 // increments current each time next JButton is pressed
 ++current;
 // if statement sets current to 0 every time the last array element is reached
 if (current == (product1.length))
 {
 current = 0;
 }
 refresh(); // calls refresh method
 }
 }
 );
 
// adds next JButton to fieldPanel
 fieldPanel.add( next );
 
// adds action listener for previous JButton
 previous.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 // sets current to last array element everytime current reaches 0
 if (current == 0)
 {
 current = product1.length;
 }
 // deincrements current every time previous JButton is pressed
 --current;
 refresh(); // calls refresh() method
 }
 }
 );
 
add.addActionListener(
 new ActionListener()
 {
 
public void actionPerformed(ActionEvent event)
 {
 
}
 }
 );
 
delete.addActionListener(
 new ActionListener()
 {
 
public void actionPerformed(ActionEvent event)
 {
 
}
 }
 );
 
modify.addActionListener(
 new ActionListener()
 {
 
public void actionPerformed(ActionEvent event)
 {
 
}
 }
 );
 
save.addActionListener(
 new ActionListener()
 {
 
public void actionPerformed(ActionEvent event)
 {
 
}
 }
 );
 
search.addActionListener(
 new ActionListener()
 {
 
public void actionPerformed(ActionEvent event)
 {
 
}
 }
 );
 
// adds previous JButton to fieldPanel
 fieldPanel.add( previous );
 
fieldPanel.add( add );
 fieldPanel.add( delete );
 fieldPanel.add( modify );
 fieldPanel.add( search );
 fieldPanel.add( save );
 
frame.add(fieldPanel); // adds fieldPanel to the JFrame
 


// Creates Font to be used for JLabel totalValue that is created below
 Font g = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 14 );
 
// creates JLabel displaying message that goes with total Value of stock
 JLabel totalValueMessage = new JLabel( " Total Value of Stock is: " );
 totalValueMessage.setFont(g); // sets font for totalValueMessage JLabel
 fieldPanel.add( totalValueMessage ); // adds totalValueMessage to fieldPanel
 
//adds JLabel totalValue to display a hard print version of the total value of stock that isn't in a text field
 JLabel totalValue = new JLabel(String.format( "$%.02f", + getTotalValue(product1)));
 totalValue.setFont(g); // sets font for totalValue JLabel
 fieldPanel.add( totalValue ); // adds JLabel to field Panel at the bottom of 2nd column
 
frame.setSize(900, 600); // sets size of JFrame
 frame.setVisible(true); // sets JFrame to be visible
 } // end main
 
// Declares method refresh()
 public static void refresh()
 {
 // sets Strings to fill JTextFields each time different JButtons are pressed
 itemNumber.setText("" + product1[current].getItemNumber());
 dvd.setText("" + product1[current].getDvd());
 producer.setText("" + product1[current].getProducer());
 units.setText(String.format("%.02f", product1[current].getUnitsAvailable()));
 price.setText(String.format("$%.02f", product1[current].getUnitPrice()));
 value.setText(String.format("$%.02f", product1[current].getValue()));
 } // end method refresh
 
// method to get the total value of the product1 array
 public static double getTotalValue( Product[] product1)
 {
 int i = 0;
 double value = 0;
 for(i = 0; i < product1.length; i++)
 {
 value += product1[i].getValue();
 }
 
return (value); 
} // end method getTotalValue
 } // end class Inventory
 

Product file:
 
package comparable.Inventory; // packages Product into comparable folder with Inventory.java
 
import javax.swing.Icon;
 import javax.swing.JPanel;
 
public class Product extends JPanel implements Comparable // allows class to be compared
 {
 // declares variables
 private double unitsAvailable;
 private double unitPrice;
 private String dvd;
 private int itemNumber;
 private double value;
 
// creates object Product for Product class
 public Product()
 {
 unitsAvailable = 0;
 unitPrice = 0;
 } // end constructor
 
// creates 4-argument constructor
 public Product( String dvd, int itemNumber, double unitsAvailable, double unitPrice )
 {
 this.dvd = dvd;
 this.itemNumber = itemNumber;
 this.unitsAvailable = unitsAvailable;
 this.unitPrice = unitPrice;
 } // end Product constructor
 
// method to get dvd name
 public String getDvd()
 {
 return dvd;
 } // end method getDvd
 
// method to get Unit price
 public double getUnitPrice()
 {
 return unitPrice;
 } // end method getUnitPrice
 
// method to get Units in stock
 public double getUnitsAvailable() 
{
 return unitsAvailable;
 } // end method getUnitsAvailable
 
// method to getItemNumber
 public int getItemNumber()
 {
 return itemNumber;
 } // end method getItemNumber
 
// method to get the value in stock
 public double getValue()
 {
 return unitsAvailable * unitPrice;
 } // end method getValue
 
// method to set the name of the dvd
 public void setDvd(String dvd)
 {
 this.dvd = dvd;
 } // end method setDvd
 
// method to set the price per unit
 public void setUnitPrice(double unitPrice)
 {
 this.unitPrice = unitPrice;
 } // end method setUnitPrice
 
// method to set the number of units in stock
 public void setUnitsInStock(double unitsInStock) 
{
 this.unitsAvailable = unitsInStock;
 } // end method setUnitsInStock
 
// method to set the item number
 public void setItemNumber(int itemNumber)
 {
 this.itemNumber = itemNumber;
 } // end method setItemNumber
 
// method to compare dvd title's in the inventory class
 public int compareTo( Object anotherProduct)
 {
 Product tmp = (Product) anotherProduct;
 
return this.getDvd().compareTo(tmp.getDvd());
 } // end method compareTo
 } // end class Product
 

ProductProducer file:
 
package comparable.Inventory;
 
public class ProductProducer extends Product
 {
 private String producer; // Producer of film
 
// five-argument constructor
 public ProductProducer( String dvd, String producer, int itemNumber, double unitsAvailable, double unitPrice)
 {
 super( dvd, itemNumber, unitsAvailable, unitPrice );
 setProducer(producer); // validates and stores producer
 } // end five-argument constructor
 
// set Producer
 public void setProducer( String producer )
 {
 this.producer = producer;
 } // end method setProducer
 
// method to get Producer
 public String getProducer()
 {
 return producer;
 } // end method getProducer
 
@Override // This method Overrides the getValue() method in its super class Product
 public double getValue()
 { 
// this statement returns the value of the Product class getValue() function * 1.05 for re-stocking fee
 return super.getValue() * 1.05;
 } // end the Override getValue()
 } // end class ProductProducer 



Is This A Good Question/Topic? 0
  • +

Replies To: Having issues with inventory program part 6 assignment

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,357
  • Joined: 02-June 10

Re: Having issues with inventory program part 6 assignment

Posted 16 February 2012 - 07:09 PM

Reminder to new folks: This is homework and we don't provide completed code for homework. Rather we try to help the student comprehend the concept they are struggling with so they can write their own code. They are being graded on their skill not ours.

This is the 'Help me with my homework' article you wanted.
Stages of asking for homework help on a forum.

Quote

The coding part isn't a problem. I just can't figure out the logic/algorythm for how this should work

That very good to hear. There are plenty of job openings for code monkeys that sit and code what they are told. They receive a detailed specification of the class/portion they need to make, what it is supposed to do, the parameters it will receive and the result it should output. That comes from an actual "Software Engineer": The person who is capable of engineering/designing/architecting the entire program, and has enough creativity to envision the entire project and see a way through it from start to end. Not everyone can do that. Its okay. But remember there is no room for advancement if all you can do is take orders. Its the difference between being the guy only capable of flipping the burgers and the guy capable of running the entire restaurant. There is a paycheck for everyone, proportionate to skill-level.
I don't want you to write my code, just give me ideas on how to solve my problem. - Read this article

"It doesn't work" isn't good enough - How you can help us, to help you

What have to you tried to code so far?
What part of what you have tried isn't working?
Are you getting error messages, or is it just not giving you the results you wanted?

(In other words, you at least have to make and show us your good faith effort to do your own coding. We are here to help you, not do it for you.)
What does this error mean?

Suggestion:
Don't replace lines of code that don't work. Instead comment them out and put your new attemps below that. This will keep you from re-trying the same ideas over and over. Also, when you come back to us saying "I've tried this 100 different ways and still can't get it", we can actually see what you tried. So often a failed attempt is very very close and just needs a little nudge in the right direction. So if we can say "See what you did in attempt 3... blah blah" it helps a lot

// Try #1 - May 1, 0900hrs
//    code
//    code  
//    code
// Try #2 - May 2, 1700hrs   Okay, plan B.  What if I do it *this* way
//    code
//    code  
//    code
// Try #14 - May 3, 0500hrs after 5 cans of RedBull.  Maybe I should get some sleep. I can't think of anything else but this last idea
    code
    code  
    code


If you are using Visual Studio you can select a block of lines and hit control+k control+c (Kode Comment) to comment it out. control+k control+u (Kode Uncomment) to uncomment a selected block.


OMG: 450+ lines of code... but no specific problem or question? Just

Quote

just not sure how to make them function to add new info to database, delete it, modify it, or save it.


Obviously that what the chapter of this week's school course, right? So you want someone here to repeat the entire lecture? What part of "don't know how" are you having trouble with? How to react to button click events? How to post queries to a database? How to get data back?

FAQ 21 is links to database tutorials.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2


FAQ (Frequently Asked Questions - Updated Feb 2012
Spoiler






please don't double post - you already had a thread going for this same thing


Was This Post Helpful? 0
  • +
  • -

#3 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,357
  • Joined: 02-June 10

Re: Having issues with inventory program part 6 assignment

Posted 16 February 2012 - 07:16 PM

I'm getting the impression that you either have a couple different accounts, or you and your study partners are working the DIC site together.

Attached Image

Attached Image


At the very least, I would observe that you are having severe trouble at each and every step of this course. I don't mean to demoralize you but I think you need to seek out your professor and let them know. Its not just one part giving you trouble: It seems to be all of it at every step. This is why we so often advice students to not bluff their way through course hoping it will magically make sense next week. It never does. It just makes an unsteady foundation for everything else to build upon. Eventually it has to come crashing down and we don't want to see that. We want you to learn.
Was This Post Helpful? 0
  • +
  • -

#4 jgammon1979  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-February 12

Re: Having issues with inventory program part 6 assignment

Posted 17 February 2012 - 01:56 AM

For one, I don't want anyone doing my homework for me. I have had my struggles, but I have always figured the code out. This one especially gots me stumped. I would just like some pointers to get started. I know I am suppose to make methods that I can call in my buttons to do the task they ask for, I just don't know what kind of code I would use. As we all know, an array can't be expanded, or shrunk after being declared. It has a set amount of variables. I need to be able to add, delete, and modify these variables. In my other post, I forgot to add the /code on the end, and didn't know how to erase the post, so I posted a new one that fixes the issue. I would like some example methods I could possibly try that would allow me to acheive what I need.
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,357
  • Joined: 02-June 10

Re: Having issues with inventory program part 6 assignment

Posted 17 February 2012 - 07:22 AM

View Postjgammon1979, on 17 February 2012 - 02:56 AM, said:

As we all know, an array can't be expanded, or shrunk after being declared. It has a set amount of variables. I need to be able to add, delete, and modify these variables.


Here's one problem that going to the professor would clear up: You are confused about the instructions and what this assignment expects of you. You are adding to a database, not adding to an array. At least that is what you told us:

Quote

I've created the buttons, just not sure how to make them function to add new info to database, delete it, modify it, or save it.


So you're premise that you have to modify your array variables is wrong.

As for extending an array. Its true that java doesn't allow resizing an array. Some other languages do. But there is a simple solution: Make a new array 1 item larger then transfer all your elements from the small array to the large array. Bam, you have a larger array.
http://www.source-co...pets/java/3.htm

Programmers of all languages did it this way for years until smarter datatypes came along (most of which do this very same thing, just behind the scenes).

Same with taking an element out of the middle. Lets say you want to do something like
myArray.RemoveAt(5);

You make a new array 1 element smaller.
In a loop,
  • copy over all the elements until you hit the specified index (5)
  • then skip that one,
  • then continue copying to the end.
  • Return the new array
.
You've just made a method that reduces your array and smartly takes an element out of the middle.

There nothing magic. There's no hidden commands you haven't learned yet. You just have to manipulate the array you have through brute force.
Was This Post Helpful? 0
  • +
  • -

#6 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Having issues with inventory program part 6 assignment

Posted 17 February 2012 - 11:46 AM

When unsure over the number of Elements going into an array it is best to use an ArrayList<Object> over an Array.

Also, when you post instead of telling us the entire project and directions for you to do, just tell us the errors that you are receiving or where you are stuck at what you've tried etc. This will avoid Homework persecution as you can see which he isn't wrong either it does at first look seem like you are wanting HW done.

When you are creating a program with multiple classes you can throw them all in 1 java file.. or you can make each of them a separate Java file in the same path. Personally I find this easier when comes to reading and debugging and having so many lines in 1 java file can seem overwhelming and discouraging.
Was This Post Helpful? 0
  • +
  • -

#7 jgammon1979  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-February 12

Re: Having issues with inventory program part 6 assignment

Posted 21 February 2012 - 12:54 AM

I figured it out after extensive studying, looking at code examples, and research. This is the final code I came up with and everything is working:



Inventory.java File

package comparable.Inventory; // packages Inventory class into comparable folder
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays; // imports java Array utility
import javax.swing.*;

import java.io.*;

public class Inventory implements Serializable // declares class Inventory
{
	 // declares new array of ProductProducer class called product1 with 6 elements
	private static ProductProducer[] product1 = new ProductProducer[6];
	private static int current = 0;
	private static JTextField itemNumber, dvd, producer, units, price, value;
	private static JLabel totalValue;
	
	// starts execution of Main function
	public static void main(String args[])
	{   
		// sets values for element 0
		product1[0] = new ProductProducer("The Darkest Hour", "Chris Gorak",
				1, 10, 12.50);
		
		// sets values for element 1
		product1[1] = new ProductProducer("The Smurfs", "Raja Gosnell",
				2, 5, 10.50);
		
		// sets values for element 2
		product1[2] = new ProductProducer("Free Runner", "Lawrence Silverstein",
				3, 25, 17.50);
		
		// sets values for element 3
		product1[3] = new ProductProducer("Happy Feet 2", "George Miller",
				4, 17, 14.50);
		
		// sets values for element 4
		product1[4] = new ProductProducer("Immortals", "Tarsem Singh",
				5, 12, 10.80);
		
		// sets values for element 5
		product1[5] = new ProductProducer("In Time", "Andrew Niccol",
				6, 9, 15.50);
		
		
		// Creates Font to be used for JText below
		Font f = new Font("Times New Roman", Font.BOLD, 24);
		
		// Creates JTextFields
		itemNumber = new JTextField(10);
		dvd = new JTextField(10);
		producer = new JTextField(10);
		units = new JTextField(10);
		price = new JTextField(10);
		value = new JTextField(10);
		
		// sorts array by dvd name
		Arrays.sort(product1);
		
		// creates JFrame with title
		JFrame frame = new JFrame( "DVD Inventory Collection" ); 
		// sets close operation for JFrame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		// creates new JPanel fieldPanel
		
		// Declares a new JPanel and calls it fieldPanel
		JPanel fieldPanel = new JPanel();
		
		// creates GridLayout for fieldPanel JPanel
		fieldPanel.setLayout( new GridLayout(7, 6));
		
		// Creates new object of logo class called picture
		Logo picture = new Logo();
		
		//adds the logo method of the logo class onto fieldPanel
		fieldPanel.add(picture.logo());
		
		// Creates JLabel to display title
		JLabel logoMessage = new JLabel("My Movie Inventory");
		logoMessage.setFont(f); // sets font of logoMessage to f font defined above
		fieldPanel.add(logoMessage); // adds logMessage to fieldPanel
		JLabel blank2 = new JLabel(); // Creates blank JLabel to skip grid
		fieldPanel.add(blank2); // adds blank label to grid
		JLabel blank3 = new JLabel(); // Creates another blank JLabel to skip another grid
		fieldPanel.add(blank3); // adds blank label to grid
		
		// creates JLabel to be used as column header for item numbers
		JLabel itemNumberLabel = new JLabel( "Item Number: " ); 
		fieldPanel.add(itemNumberLabel); // adds new JLabel to fieldPanel
		fieldPanel.add(itemNumber); // adds JTextField to fieldPanel
		
		// creates JLabel to be used as column header for dvd titles
		JLabel dvdLabel = new JLabel( " Dvd title: " ); 
		fieldPanel.add( dvdLabel ); // adds new JLabel to fieldPanel
		fieldPanel.add( dvd ); // adds JTextField to fieldPanel
		
		// creates JLabel to be used as column header for producers
		JLabel producerLabel = new JLabel( " Producer: " ); 
		fieldPanel.add( producerLabel );  // adds new JLabel to fieldPanel
		fieldPanel.add( producer ); // adds JTextField to fieldPanel
		
		// creates JLabel to be used as column header for Units
		JLabel unitsLabel = new JLabel( " Units: " ); 
		fieldPanel.add( unitsLabel ); // adds new JLabel to fieldPanel
		fieldPanel.add( units ); // adds JTextField to fieldPanel
		
		// creates JLabel to be used as column header for Prices
		JLabel priceLabel = new JLabel( " Price: " );  
		fieldPanel.add( priceLabel );  // adds new JLabel to fieldPanel
		fieldPanel.add( price ); // adds JTextField to fieldPanel
		
		// creates JLabel to be used as column header for Values
		JLabel valueLabel = new JLabel( " Value: " ); 
		fieldPanel.add( valueLabel ); // adds new JLabel to fieldPanel
		fieldPanel.add( value ); // adds JTextField to fieldPanel
		
		
		// Declares 4 JButtons and gives them names
		JButton first = new JButton( "First Item" );
		JButton last = new JButton( "Last Item" );
		JButton previous = new JButton( "Previous Item" );
		JButton next = new JButton( "Next Item" );
		JButton add = new JButton( "Add" );
		JButton delete = new JButton( "Delete" );
		JButton modify = new JButton( "Modify" );
		JButton save = new JButton( "Save" );
		JButton search = new JButton( "Search" );
		
		// Creates action listener for first JButton
		first.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					current = 0;
					refresh();
				}
			}
		);
		
		// adds first JButton to fieldPanel
		fieldPanel.add( first );
		
		// Creates action listener for last JButton
		last.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					current = product1.length - 1;
					refresh(); // calls method refresh to update GUI
				}
			}
		);
		
		// adds last JButton to fieldPanel
		fieldPanel.add( last );
		
		// Creates action listener for next JButton
		next.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					// increments current each time next JButton is pressed
					++current;
					// if statement sets current to 0 every time the last array element is reached
					if (current == (product1.length))
					{
						current = 0;
					}
					refresh(); // calls refresh method
				}
			}
		);
		
		// adds next JButton to fieldPanel
		fieldPanel.add( next );
		
		// adds action listener for previous JButton
		previous.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					// sets current to last array element every time current reaches 0
					if (current == 0)
					{
						current = product1.length;
					}
					// deincrements current every time previous JButton is pressed
					--current;
					refresh();	// calls refresh() method
				}
			}
		);
		
		// adds previous JButton to fieldPanel
		fieldPanel.add( previous );
		
		// adds action listener for add JButton
		add.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					addItem(); // calls method addItem
					refresh(); // calls method refresh
				}
			} 
		);
		
		fieldPanel.add( add ); // adds add JButton to fieldPanel
		
		// adds action listener for delete JButton
		delete.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					deleteItem(); // calls method deleteItem
					refresh(); // calls method refresh
				}
			}
		);
			
		fieldPanel.add( delete ); // adds delete JButton to fieldPanel
		
		// adds action listener for modify JButton
		modify.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					modifyItem(); // calls method modifyItem
					refresh(); // calls method refresh
				}
			}
		);
				
		fieldPanel.add( modify ); // adds modify JButton to fieldPanel
		
		// adds action listener for save JButton
		save.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					saveItem(); // calls saveItem method
					refresh(); // calls refresh method
				}
			}
		);
			
		fieldPanel.add( save ); // adds save JButton to fieldPanel
		
		// adds action listener for search JButton
		search.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					searchItem(); // calls searchItem method
					refresh(); // calls refresh method
				}
			} 
		); 
			
		fieldPanel.add( search ); // adds search JButton to fieldPanel
		
		frame.add(fieldPanel); // adds fieldPanel to the JFrame	
			
		// Creates Font to be used for JLabel totalValue that is created below
		Font g = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 14 );
				
		// creates JLabel displaying message that goes with total Value of stock
		JLabel totalValueMessage = new JLabel( "      Total Value of Stock is: " );
			totalValueMessage.setFont(g); // sets font for totalValueMessage JLabel
			fieldPanel.add( totalValueMessage ); // adds totalValueMessage to fieldPanel
		
		//adds JLabel totalValue to display a hard print version of the total value of stock that isn't in a text field
			totalValue = new JLabel(String.format( "$%.02f", + getTotalValue(product1)));
			totalValue.setFont(g); // sets font for totalValue JLabel
			fieldPanel.add( totalValue ); // adds JLabel to field Panel at the bottom of 2nd column
		
		frame.setSize(900, 650);  // sets size of JFrame
		frame.setVisible(true); // sets JFrame to be visible
	} // end main
	
	// Declares method refresh()
	public static void refresh()
	{
		// sets Strings to fill JTextFields each time different JButtons are pressed
		itemNumber.setText("" + product1[current].getItemNumber());
		dvd.setText("" + product1[current].getDvd());
		producer.setText("" + product1[current].getProducer());
		units.setText(String.format("%.02f", product1[current].getUnitsAvailable()));
		price.setText(String.format("$%.02f", product1[current].getUnitPrice()));
		value.setText(String.format("$%.02f", product1[current].getValue()));
		totalValue.setText(String.format("$%.02f", +getTotalValue(product1)));
	}  // end method refresh
	
	// method to get the total value of the product1 array
	public static double getTotalValue( Product[] product1)
	{
		 double value = 0; // initializes variable value
         for(int i = 0; i < product1.length; i++)
         {
             value += product1[i].getValue();
         } // end for 
         return (value); // returns the value of the value variable	
	} // end method getTotalValue
	
	//method to add item
    static void addItem() 
    {
        int itemNumber; //  item number for dvd
        String dvdName; //  name of dvd
        String producer; // name of producer of dvd
        double unitsTotal;  // total  units in inventory
        double price; // price per unit
        
        // initiates itemNumber to be equal to first element of product1 array's item number
        itemNumber = product1[0].getItemNumber();
        
        // makes sure that the variable itemNumber is greater than product1 arrays item numbers
        for (int i = 0; i < product1.length; i++) 
        {
            if (product1[i].getItemNumber() > itemNumber) 
            {
                itemNumber = product1[i].getItemNumber(); // sets itemNumber greater than previous element's item number
            } // end if
        } // end for
        // increments itemNumber by 1 more than the previous item number
        itemNumber++;

        // initiates the variable count and sets it to 1 more than the length of product1's array
        int count = product1.length + 1;

        // Declares new temp array that has 1 more element that product1's array
        ProductProducer temp[] = new ProductProducer[count];
        
        // uses JOptionPane to provide an input box to enter information in.
        dvdName = JOptionPane.showInputDialog("Enter the name of the Dvd:");
        unitsTotal = Double.parseDouble(JOptionPane.showInputDialog("Enter Units:"));
        price = Double.parseDouble(JOptionPane.showInputDialog("Enter price:"));
        producer = JOptionPane.showInputDialog("Enter producer:");
        
        // creates new object of ProductProducer class and calls it product2
        ProductProducer product2 = new ProductProducer(dvdName, producer, itemNumber, unitsTotal, price);
        
        // copies value of elements from product1 into new temp array
        for (int i = 0; i < product1.length; i++) 
        {
            temp[i] = product1[i];
        } // end for
        // sets last element's value equal to product2
        temp[count - 1] = product2;
        // sets product1 to equal temp
        product1 = temp;
        
        // shows message dialog stating new item was added
        JOptionPane.showMessageDialog(null, "Item " + product2.getItemNumber() +
        	" has been added to inventory.");
        refresh();
    } // end addItem method
    
    // Declares method deleteItem
    static void deleteItem() 
    {
        int number = Integer.parseInt(JOptionPane.showInputDialog("Enter number to delete:"));

        // initializes variable a to be used as an indicator
        int a = -1;
        // loops through elements in product1 to see if anything matches the number entered
        for (int i = 0; i < product1.length; i++)
        {
            if (product1[i].getItemNumber() == number) 
            {
                a = i; // if the number is found a set to equal that element number
            } // end if
        } // end for
        // if a number is not found in the inventory, a stay equal to -1 and less than 0
        if (a < 0) 
        {
            JOptionPane.showMessageDialog(null, "Number not found"); // This displays a message saying the number wasn't found
        } // end if
        
        // creates a new array called temp and gives it one less element than the product1 array
        ProductProducer temp[] = new ProductProducer[product1.length - 1];
        int j = 0; // initializes the variable j
        
        // loops through the product1 array
        for (int i = 0; i < product1.length; i++) 
        {
            if (i == a) // if i is equal to a because the number was found will continue to next function
            {
                continue; // continues with deletion process skipping rest of loop
            } // end if
            else 
            {
                temp[j] = product1[i]; // if number wasn't found temp will equal product1's array
                j++; // j is incremented along with product1 for each iteration of the for loop
            } // end else
        } // end for
        
        product1 = temp; // product1 is set to equal temp

        // if the value of current is greater than the length of product1 - 1 then current is reset to 0
        if (current > product1.length - 1) 
        {
            current = 0;
        } // end if
        
        // shows message dialog indicating item was deleted
        JOptionPane.showMessageDialog(null, "Item " + number + " was deleted" );
        refresh(); // calls the refresh method
    } // end method deleteItem
    
    // Declares method saveItem
    static void saveItem() 
    {
        try 
        { 	// Creates new BufferedWriter and FileWriter to write data to C:\data\inventory.dat file
            BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));

            // loops through product1 array writing each elements information to C:\data\inventory.dat
            for (int i = 0; i < product1.length; i++) 
            {
                ProductProducer save = product1[i]; // creates save object to equal the product1 array
                
                /** I couldn't get the /n to work to send information to a new line
                 *  so I got rid of the msg String here and just used the BufferedWriter
                 *  commands directly for each instance.  I used the BufferedWriter's
                 *  newLine method to make spaces so it would look nice and neat in
                 *  a text editor, or windows note pad. I used the newLine method to
                 *  double space between each elements information, and the next one.
                 */
                w.write("Item Number: " + save.getItemNumber()); // writes each item number to file
                w.newLine(); // starts new line
                w.write("Dvd Title: " + save.getDvd()); // writes each Dvd Title to file
                w.newLine(); // starts new line
                w.write("Producer: " + save.getProducer()); // writes each Producer to file
                w.newLine(); // starts new line
                w.write("Number of Units in Stock: " + save.getUnitsAvailable()); // writes each unit in stock to file
                w.newLine(); // starts new line
                w.write("Unit Price: " + String.format("$%.02f", save.getUnitPrice())); // writes each unit Price to file
                w.newLine(); // starts new line
                w.write("Value: " + String.format("$%.02f", save.getValue())); // write each Value to file with 5% re-stocking fee included
                w.newLine(); // starts new line
                w.newLine(); // creates a line space between previous elements information and next one
            } // end for
            // writes total value
            w.write("Total Inventory Value with restocking fee included: " + String.format("$%.02f", getTotalValue(product1)));           
            w.close(); // ends writing process
            
            // Displays message Dialog showing that data was saved
            JOptionPane.showMessageDialog(null, "Inventory has been Saved");
        } // end try
        catch (Exception ex) // catches instance where C:\data doesn't exist yet
        {
            JOptionPane.showConfirmDialog(null, ex);
            new File("c:\\data\\").mkdir(); // creates directory c:\data if it doesn't exist
            saveItem(); // goes through saveItem function again to save data in newly created directory
            
            //Shows message that information was saves as C:\data\inventory.dat
            JOptionPane.showMessageDialog(null, "Saved as c:\\data\\inventory.dat");
        } // end catch
    } // end method saveItem
    
    // Declares method modifyItem
    static void modifyItem() 
    {
    	int itemNumber; //  item number for dvd
        String dvdName; //  name of dvd
        String producer; // name of producer of dvd
        double unitsTotal;  // total  units in inventory
        double price; // price per unit
        
        // displays window that allows for the item number to be modified to be entered
        itemNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter number to modify:"));
        
        // initializes b to be indicator
        int b = -1;
        // loops through product1 array
        for (int i = 0; i < product1.length; i++)
        {
            if (product1[i].getItemNumber() == itemNumber) 
            {
                b = i; // if the item number is found b is set to equal that element number
            } // end if
        } // end for
        // if the number isn't found then b stays equal to -1 and thus is less than 0
        if (b < 0)
        {
        	// displays message that the itemNumber wasn't found
            JOptionPane.showMessageDialog(null, "Number not found");
        } // end if
        // opens set of dialog windows allowing new information to be entered for the item number that was found
        dvdName = JOptionPane.showInputDialog("Enter DVD title:");
        unitsTotal = Double.parseDouble(JOptionPane.showInputDialog("Enter Units:"));
        price = Double.parseDouble(JOptionPane.showInputDialog("Enter Price:"));
        producer = JOptionPane.showInputDialog("Enter Producer:");
        
        // sets input entered in dialog box to replace the setters
        // in the specified element containing the item number entered
        product1[b].setDvd(dvdName); // sets Dvd title to new value
        product1[b].setUnitsInStock(unitsTotal); // sets Units to new value
        product1[b].setUnitPrice(price); // sets Unit Price to new value
        product1[b].setProducer(producer); // sets producer to new value
        
        // Shows message dialog indicating that the item has been modified
        JOptionPane.showMessageDialog(null, "Item " + itemNumber +
        	" has been modified");
        refresh(); // calls the refresh method
    } // end method modifyItem
    
    // declares method searchItem
    static void searchItem() 
    {
        String dvdTitle; // Name of Dvd

        // displays dialog message for input of item number being searched for
        dvdTitle = JOptionPane.showInputDialog("Enter the Name of the Dvd Title your looking for:");
        
        int c = -1; // initializes variable c as an indicator
        
        // loops through the product1 array looking for item number
        for (int i = 0; i < product1.length; i++) 
        {
        	// compares each string element of getDvd to that of the input entered
            if ((product1[i].getDvd()).equalsIgnoreCase(dvdTitle)) 
            {
                c = i; // if the number entered in dialog is found in array c is set to equal the array element
                current = c; // sets current item to item found location
            } // end if
        } // end for
        
        refresh(); // Updates the view to the item found location
        
        if (c < 0) // if number inputed is not in array, then c remains equal to -1 and is less than 0
        {
        	// Displays message dialog if number is not found in product1 array
            JOptionPane.showMessageDialog(null, "Dvd not found");
            return; // returns to main since nothing was found
        } // end if
    } // end searchItem method
} // end class Inventory



File Product.java

package comparable.Inventory; // packages Product into comparable folder with Inventory.java

import javax.swing.JPanel;

public class Product extends JPanel implements Comparable // allows class to be compared
{
	// declares variables
	private double unitsAvailable;
	private double unitPrice;
	private String dvd;
	private int itemNumber;
	
	// creates object Product for Product class
	public Product()
	{
		unitsAvailable = 0;
		unitPrice = 0;
	} // end constructor
	
	// creates 4-argument constructor
	public Product( String dvd, int itemNumber, double unitsAvailable, double unitPrice )
	{
		this.dvd = dvd;
		this.itemNumber = itemNumber;
		this.unitsAvailable = unitsAvailable;
		this.unitPrice = unitPrice;
	} // end Product constructor

	// method to get dvd name
	public String getDvd()
	{
		return dvd;
	} // end method getDvd
	
	// method to get Unit price
	public double getUnitPrice()
	{
		return unitPrice;
	} // end method getUnitPrice
	
	// method to get Units in stock
	public double getUnitsAvailable() 
	{
		return unitsAvailable;
	} // end method getUnitsAvailable
	
	// method to getItemNumber
	public int getItemNumber()
	{
		return itemNumber;
	} // end method getItemNumber
	
	// method to get the value in stock
	public double getValue()
	{
		return unitsAvailable * unitPrice;
	} // end method getValue
	
	// method to set the name of the dvd
	public void setDvd(String dvd)
	{
		this.dvd = dvd;
	} // end method setDvd
	
	// method to set the price per unit
	public void setUnitPrice(double unitPrice)
	{
		this.unitPrice = unitPrice;
	} // end method setUnitPrice
	
	// method to set the number of units in stock
	public void setUnitsInStock(double unitsInStock) 
	{
		this.unitsAvailable = unitsInStock;
	} // end method setUnitsInStock
	
	// method to set the item number
	public void setItemNumber(int itemNumber)
	{
		this.itemNumber = itemNumber;
	} // end method setItemNumber
	
	// method to compare dvd title's in the inventory class
	public int compareTo( Object anotherProduct)
	{
	     Product tmp = (Product) anotherProduct;
	     
	     return this.getDvd().compareTo(tmp.getDvd());
	} // end method compareTo
} // end class Product



ProductProducer.java file

package comparable.Inventory;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ProductProducer extends Product
{
	private String producer;  // Producer of film
	
	// five-argument constructor
	public ProductProducer( String dvd, String producer, int itemNumber, double unitsAvailable, double unitPrice)
	{
		super( dvd, itemNumber, unitsAvailable, unitPrice );
		setProducer(producer); // validates and stores producer
	} // end five-argument constructor

	// set Producer
	public void setProducer( String producer )
	{
		this.producer = producer;
	} // end method setProducer
	
	// method to get Producer
	public String getProducer()
	{
		return producer;
	} // end method getProducer
	
	@Override // This method Overrides the getValue() method in its super class Product
	public double getValue()
	{	
		// this statement returns the value of the Product class getValue() function * 1.05 for re-stocking fee
		return super.getValue() * 1.05;
	} // end the Override getValue()
} // end class ProductProducer



logo.java file

package comparable.Inventory; // uses package comparable.Inventory

import javax.swing.ImageIcon; // imports javax.swing's ImagIcon method
import javax.swing.JLabel; // imports javax.swing's JLabel method

// declares class Logo
public class Logo 
{
	// Declares method logo to display the image.png picture
	public JLabel logo()
	{	
		// creates ImageIcon for image.png in bin folder
		ImageIcon image = new ImageIcon(getClass().getResource("image.png"));
					
		// Creates new JLabel and fills it with image.png
		JLabel picture = new JLabel(image);
		return (picture); // returns picture as a JLabel
	} // end method logo
} // end class Logo

This post has been edited by smohd: 24 February 2012 - 04:17 PM
Reason for edit:: Code tags added. Please use [code] tags when posting codes

Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,357
  • Joined: 02-June 10

Re: Having issues with inventory program part 6 assignment

Posted 22 February 2012 - 08:25 AM

Please fix your fraking code tags!
Its not that hard to get them right.
:code:
Was This Post Helpful? 0
  • +
  • -

#9 jgammon1979  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 03-February 12

Re: Having issues with inventory program part 6 assignment

Posted 24 February 2012 - 03:10 PM

Sorry about that, forgot to put the /code at the end.

I figured it out after extensive studying, looking at code examples, and research. This is the final code I came up with and everything is working:

 
Inventory.java File
 
package comparable.Inventory; // packages Inventory class into comparable folder
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.util.Arrays; // imports java Array utility
 import javax.swing.*;
 
import java.io.*;
 
public class Inventory implements Serializable // declares class Inventory
 {
 // declares new array of ProductProducer class called product1 with 6 elements
 private static ProductProducer[] product1 = new ProductProducer[6];
 private static int current = 0;
 private static JTextField itemNumber, dvd, producer, units, price, value;
 private static JLabel totalValue;
 
// starts execution of Main function
 public static void main(String args[])
 { 
// sets values for element 0
 product1[0] = new ProductProducer("The Darkest Hour", "Chris Gorak",
 1, 10, 12.50);
 
// sets values for element 1
 product1[1] = new ProductProducer("The Smurfs", "Raja Gosnell",
 2, 5, 10.50);
 
// sets values for element 2
 product1[2] = new ProductProducer("Free Runner", "Lawrence Silverstein",
 3, 25, 17.50);
 
// sets values for element 3
 product1[3] = new ProductProducer("Happy Feet 2", "George Miller",
 4, 17, 14.50);
 
// sets values for element 4
 product1[4] = new ProductProducer("Immortals", "Tarsem Singh",
 5, 12, 10.80);
 
// sets values for element 5
 product1[5] = new ProductProducer("In Time", "Andrew Niccol",
 6, 9, 15.50);
 

// Creates Font to be used for JText below
 Font f = new Font("Times New Roman", Font.BOLD, 24);
 
// Creates JTextFields
 itemNumber = new JTextField(10);
 dvd = new JTextField(10);
 producer = new JTextField(10);
 units = new JTextField(10);
 price = new JTextField(10);
 value = new JTextField(10);
 
// sorts array by dvd name
 Arrays.sort(product1);
 
// creates JFrame with title
 JFrame frame = new JFrame( "DVD Inventory Collection" ); 
// sets close operation for JFrame
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
// creates new JPanel fieldPanel
 
// Declares a new JPanel and calls it fieldPanel
 JPanel fieldPanel = new JPanel();
 
// creates GridLayout for fieldPanel JPanel
 fieldPanel.setLayout( new GridLayout(7, 6));
 
// Creates new object of logo class called picture
 Logo picture = new Logo();
 
//adds the logo method of the logo class onto fieldPanel
 fieldPanel.add(picture.logo());
 
// Creates JLabel to display title
 JLabel logoMessage = new JLabel("My Movie Inventory");
 logoMessage.setFont(f); // sets font of logoMessage to f font defined above
 fieldPanel.add(logoMessage); // adds logMessage to fieldPanel
 JLabel blank2 = new JLabel(); // Creates blank JLabel to skip grid
 fieldPanel.add(blank2); // adds blank label to grid
 JLabel blank3 = new JLabel(); // Creates another blank JLabel to skip another grid
 fieldPanel.add(blank3); // adds blank label to grid
 
// creates JLabel to be used as column header for item numbers
 JLabel itemNumberLabel = new JLabel( "Item Number: " ); 
fieldPanel.add(itemNumberLabel); // adds new JLabel to fieldPanel
 fieldPanel.add(itemNumber); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for dvd titles
 JLabel dvdLabel = new JLabel( " Dvd title: " ); 
fieldPanel.add( dvdLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( dvd ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for producers
 JLabel producerLabel = new JLabel( " Producer: " ); 
fieldPanel.add( producerLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( producer ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Units
 JLabel unitsLabel = new JLabel( " Units: " ); 
fieldPanel.add( unitsLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( units ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Prices
 JLabel priceLabel = new JLabel( " Price: " ); 
fieldPanel.add( priceLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( price ); // adds JTextField to fieldPanel
 
// creates JLabel to be used as column header for Values
 JLabel valueLabel = new JLabel( " Value: " ); 
fieldPanel.add( valueLabel ); // adds new JLabel to fieldPanel
 fieldPanel.add( value ); // adds JTextField to fieldPanel
 

// Declares 4 JButtons and gives them names
 JButton first = new JButton( "First Item" );
 JButton last = new JButton( "Last Item" );
 JButton previous = new JButton( "Previous Item" );
 JButton next = new JButton( "Next Item" );
 JButton add = new JButton( "Add" );
 JButton delete = new JButton( "Delete" );
 JButton modify = new JButton( "Modify" );
 JButton save = new JButton( "Save" );
 JButton search = new JButton( "Search" );
 
// Creates action listener for first JButton
 first.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 current = 0;
 refresh();
 }
 }
 );
 
// adds first JButton to fieldPanel
 fieldPanel.add( first );
 
// Creates action listener for last JButton
 last.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 current = product1.length - 1;
 refresh(); // calls method refresh to update GUI
 }
 }
 );
 
// adds last JButton to fieldPanel
 fieldPanel.add( last );
 
// Creates action listener for next JButton
 next.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 // increments current each time next JButton is pressed
 ++current;
 // if statement sets current to 0 every time the last array element is reached
 if (current == (product1.length))
 {
 current = 0;
 }
 refresh(); // calls refresh method
 }
 }
 );
 
// adds next JButton to fieldPanel
 fieldPanel.add( next );
 
// adds action listener for previous JButton
 previous.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 // sets current to last array element every time current reaches 0
 if (current == 0)
 {
 current = product1.length;
 }
 // deincrements current every time previous JButton is pressed
 --current;
 refresh(); // calls refresh() method
 }
 }
 );
 
// adds previous JButton to fieldPanel
 fieldPanel.add( previous );
 
// adds action listener for add JButton
 add.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 addItem(); // calls method addItem
 refresh(); // calls method refresh
 }
 } 
);
 
fieldPanel.add( add ); // adds add JButton to fieldPanel
 
// adds action listener for delete JButton
 delete.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 deleteItem(); // calls method deleteItem
 refresh(); // calls method refresh
 }
 }
 );
 
fieldPanel.add( delete ); // adds delete JButton to fieldPanel
 
// adds action listener for modify JButton
 modify.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 modifyItem(); // calls method modifyItem
 refresh(); // calls method refresh
 }
 }
 );
 
fieldPanel.add( modify ); // adds modify JButton to fieldPanel
 
// adds action listener for save JButton
 save.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 saveItem(); // calls saveItem method
 refresh(); // calls refresh method
 }
 }
 );
 
fieldPanel.add( save ); // adds save JButton to fieldPanel
 
// adds action listener for search JButton
 search.addActionListener(
 new ActionListener()
 {
 public void actionPerformed(ActionEvent event)
 {
 searchItem(); // calls searchItem method
 refresh(); // calls refresh method
 }
 } 
); 

fieldPanel.add( search ); // adds search JButton to fieldPanel
 
frame.add(fieldPanel); // adds fieldPanel to the JFrame 

// Creates Font to be used for JLabel totalValue that is created below
 Font g = new Font("Times New Roman", Font.BOLD + Font.ITALIC, 14 );
 
// creates JLabel displaying message that goes with total Value of stock
 JLabel totalValueMessage = new JLabel( " Total Value of Stock is: " );
 totalValueMessage.setFont(g); // sets font for totalValueMessage JLabel
 fieldPanel.add( totalValueMessage ); // adds totalValueMessage to fieldPanel
 
//adds JLabel totalValue to display a hard print version of the total value of stock that isn't in a text field
 totalValue = new JLabel(String.format( "$%.02f", + getTotalValue(product1)));
 totalValue.setFont(g); // sets font for totalValue JLabel
 fieldPanel.add( totalValue ); // adds JLabel to field Panel at the bottom of 2nd column
 
frame.setSize(900, 650); // sets size of JFrame
 frame.setVisible(true); // sets JFrame to be visible
 } // end main
 
// Declares method refresh()
 public static void refresh()
 {
 // sets Strings to fill JTextFields each time different JButtons are pressed
 itemNumber.setText("" + product1[current].getItemNumber());
 dvd.setText("" + product1[current].getDvd());
 producer.setText("" + product1[current].getProducer());
 units.setText(String.format("%.02f", product1[current].getUnitsAvailable()));
 price.setText(String.format("$%.02f", product1[current].getUnitPrice()));
 value.setText(String.format("$%.02f", product1[current].getValue()));
 totalValue.setText(String.format("$%.02f", +getTotalValue(product1)));
 } // end method refresh
 
// method to get the total value of the product1 array
 public static double getTotalValue( Product[] product1)
 {
 double value = 0; // initializes variable value
 for(int i = 0; i < product1.length; i++)
 {
 value += product1[i].getValue();
 } // end for 
return (value); // returns the value of the value variable 
} // end method getTotalValue
 
//method to add item
 static void addItem() 
{
 int itemNumber; // item number for dvd
 String dvdName; // name of dvd
 String producer; // name of producer of dvd
 double unitsTotal; // total units in inventory
 double price; // price per unit
 
// initiates itemNumber to be equal to first element of product1 array's item number
 itemNumber = product1[0].getItemNumber();
 
// makes sure that the variable itemNumber is greater than product1 arrays item numbers
 for (int i = 0; i < product1.length; i++) 
{
 if (product1[i].getItemNumber() > itemNumber) 
{
 itemNumber = product1[i].getItemNumber(); // sets itemNumber greater than previous element's item number
 } // end if
 } // end for
 // increments itemNumber by 1 more than the previous item number
 itemNumber++;
 
// initiates the variable count and sets it to 1 more than the length of product1's array
 int count = product1.length + 1;
 
// Declares new temp array that has 1 more element that product1's array
 ProductProducer temp[] = new ProductProducer[count];
 
// uses JOptionPane to provide an input box to enter information in.
 dvdName = JOptionPane.showInputDialog("Enter the name of the Dvd:");
 unitsTotal = Double.parseDouble(JOptionPane.showInputDialog("Enter Units:"));
 price = Double.parseDouble(JOptionPane.showInputDialog("Enter price:"));
 producer = JOptionPane.showInputDialog("Enter producer:");
 
// creates new object of ProductProducer class and calls it product2
 ProductProducer product2 = new ProductProducer(dvdName, producer, itemNumber, unitsTotal, price);
 
// copies value of elements from product1 into new temp array
 for (int i = 0; i < product1.length; i++) 
{
 temp[i] = product1[i];
 } // end for
 // sets last element's value equal to product2
 temp[count - 1] = product2;
 // sets product1 to equal temp
 product1 = temp;
 
// shows message dialog stating new item was added
 JOptionPane.showMessageDialog(null, "Item " + product2.getItemNumber() +
 " has been added to inventory.");
 refresh();
 } // end addItem method
 
// Declares method deleteItem
 static void deleteItem() 
{
 int number = Integer.parseInt(JOptionPane.showInputDialog("Enter number to delete:"));
 
// initializes variable a to be used as an indicator
 int a = -1;
 // loops through elements in product1 to see if anything matches the number entered
 for (int i = 0; i < product1.length; i++)
 {
 if (product1[i].getItemNumber() == number) 
{
 a = i; // if the number is found a set to equal that element number
 } // end if
 } // end for
 // if a number is not found in the inventory, a stay equal to -1 and less than 0
 if (a < 0) 
{
 JOptionPane.showMessageDialog(null, "Number not found"); // This displays a message saying the number wasn't found
 } // end if
 
// creates a new array called temp and gives it one less element than the product1 array
 ProductProducer temp[] = new ProductProducer[product1.length - 1];
 int j = 0; // initializes the variable j
 
// loops through the product1 array
 for (int i = 0; i < product1.length; i++) 
{
 if (i == a) // if i is equal to a because the number was found will continue to next function
 {
 continue; // continues with deletion process skipping rest of loop
 } // end if
 else 
{
 temp[j] = product1[i]; // if number wasn't found temp will equal product1's array
 j++; // j is incremented along with product1 for each iteration of the for loop
 } // end else
 } // end for
 
product1 = temp; // product1 is set to equal temp
 
// if the value of current is greater than the length of product1 - 1 then current is reset to 0
 if (current > product1.length - 1) 
{
 current = 0;
 } // end if
 
// shows message dialog indicating item was deleted
 JOptionPane.showMessageDialog(null, "Item " + number + " was deleted" );
 refresh(); // calls the refresh method
 } // end method deleteItem
 
// Declares method saveItem
 static void saveItem() 
{
 try 
{ // Creates new BufferedWriter and FileWriter to write data to C:\data\inventory.dat file
 BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));
 
// loops through product1 array writing each elements information to C:\data\inventory.dat
 for (int i = 0; i < product1.length; i++) 
{
 ProductProducer save = product1[i]; // creates save object to equal the product1 array
 
/** I couldn't get the /n to work to send information to a new line
 * so I got rid of the msg String here and just used the BufferedWriter
 * commands directly for each instance. I used the BufferedWriter's
 * newLine method to make spaces so it would look nice and neat in
 * a text editor, or windows note pad. I used the newLine method to
 * double space between each elements information, and the next one.
 */
 w.write("Item Number: " + save.getItemNumber()); // writes each item number to file
 w.newLine(); // starts new line
 w.write("Dvd Title: " + save.getDvd()); // writes each Dvd Title to file
 w.newLine(); // starts new line
 w.write("Producer: " + save.getProducer()); // writes each Producer to file
 w.newLine(); // starts new line
 w.write("Number of Units in Stock: " + save.getUnitsAvailable()); // writes each unit in stock to file
 w.newLine(); // starts new line
 w.write("Unit Price: " + String.format("$%.02f", save.getUnitPrice())); // writes each unit Price to file
 w.newLine(); // starts new line
 w.write("Value: " + String.format("$%.02f", save.getValue())); // write each Value to file with 5% re-stocking fee included
 w.newLine(); // starts new line
 w.newLine(); // creates a line space between previous elements information and next one
 } // end for
 // writes total value
 w.write("Total Inventory Value with restocking fee included: " + String.format("$%.02f", getTotalValue(product1))); 
w.close(); // ends writing process
 
// Displays message Dialog showing that data was saved
 JOptionPane.showMessageDialog(null, "Inventory has been Saved");
 } // end try
 catch (Exception ex) // catches instance where C:\data doesn't exist yet
 {
 JOptionPane.showConfirmDialog(null, ex);
 new File("c:\\data\\").mkdir(); // creates directory c:\data if it doesn't exist
 saveItem(); // goes through saveItem function again to save data in newly created directory
 
//Shows message that information was saves as C:\data\inventory.dat
 JOptionPane.showMessageDialog(null, "Saved as c:\\data\\inventory.dat");
 } // end catch
 } // end method saveItem
 
// Declares method modifyItem
 static void modifyItem() 
{
 int itemNumber; // item number for dvd
 String dvdName; // name of dvd
 String producer; // name of producer of dvd
 double unitsTotal; // total units in inventory
 double price; // price per unit
 
// displays window that allows for the item number to be modified to be entered
 itemNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter number to modify:"));
 
// initializes b to be indicator
 int b = -1;
 // loops through product1 array
 for (int i = 0; i < product1.length; i++)
 {
 if (product1[i].getItemNumber() == itemNumber) 
{
 b = i; // if the item number is found b is set to equal that element number
 } // end if
 } // end for
 // if the number isn't found then b stays equal to -1 and thus is less than 0
 if (b < 0)
 {
 // displays message that the itemNumber wasn't found
 JOptionPane.showMessageDialog(null, "Number not found");
 } // end if
 // opens set of dialog windows allowing new information to be entered for the item number that was found
 dvdName = JOptionPane.showInputDialog("Enter DVD title:");
 unitsTotal = Double.parseDouble(JOptionPane.showInputDialog("Enter Units:"));
 price = Double.parseDouble(JOptionPane.showInputDialog("Enter Price:"));
 producer = JOptionPane.showInputDialog("Enter Producer:");
 
// sets input entered in dialog box to replace the setters
 // in the specified element containing the item number entered
 product1[b].setDvd(dvdName); // sets Dvd title to new value
 product1[b].setUnitsInStock(unitsTotal); // sets Units to new value
 product1[b].setUnitPrice(price); // sets Unit Price to new value
 product1[b].setProducer(producer); // sets producer to new value
 
// Shows message dialog indicating that the item has been modified
 JOptionPane.showMessageDialog(null, "Item " + itemNumber +
 " has been modified");
 refresh(); // calls the refresh method
 } // end method modifyItem
 
// declares method searchItem
 static void searchItem() 
{
 String dvdTitle; // Name of Dvd
 
// displays dialog message for input of item number being searched for
 dvdTitle = JOptionPane.showInputDialog("Enter the Name of the Dvd Title your looking for:");
 
int c = -1; // initializes variable c as an indicator
 
// loops through the product1 array looking for item number
 for (int i = 0; i < product1.length; i++) 
{
 // compares each string element of getDvd to that of the input entered
 if ((product1[i].getDvd()).equalsIgnoreCase(dvdTitle)) 
{
 c = i; // if the number entered in dialog is found in array c is set to equal the array element
 current = c; // sets current item to item found location
 } // end if
 } // end for
 
refresh(); // Updates the view to the item found location
 
if (c < 0) // if number inputed is not in array, then c remains equal to -1 and is less than 0
 {
 // Displays message dialog if number is not found in product1 array
 JOptionPane.showMessageDialog(null, "Dvd not found");
 return; // returns to main since nothing was found
 } // end if
 } // end searchItem method
 } // end class Inventory
 

File Product.java
 
package comparable.Inventory; // packages Product into comparable folder with Inventory.java
 
import javax.swing.JPanel;
 
public class Product extends JPanel implements Comparable // allows class to be compared
 {
 // declares variables
 private double unitsAvailable;
 private double unitPrice;
 private String dvd;
 private int itemNumber;
 
// creates object Product for Product class
 public Product()
 {
 unitsAvailable = 0;
 unitPrice = 0;
 } // end constructor
 
// creates 4-argument constructor
 public Product( String dvd, int itemNumber, double unitsAvailable, double unitPrice )
 {
 this.dvd = dvd;
 this.itemNumber = itemNumber;
 this.unitsAvailable = unitsAvailable;
 this.unitPrice = unitPrice;
 } // end Product constructor
 
// method to get dvd name
 public String getDvd()
 {
 return dvd;
 } // end method getDvd
 
// method to get Unit price
 public double getUnitPrice()
 {
 return unitPrice;
 } // end method getUnitPrice
 
// method to get Units in stock
 public double getUnitsAvailable() 
{
 return unitsAvailable;
 } // end method getUnitsAvailable
 
// method to getItemNumber
 public int getItemNumber()
 {
 return itemNumber;
 } // end method getItemNumber
 
// method to get the value in stock
 public double getValue()
 {
 return unitsAvailable * unitPrice;
 } // end method getValue
 
// method to set the name of the dvd
 public void setDvd(String dvd)
 {
 this.dvd = dvd;
 } // end method setDvd
 
// method to set the price per unit
 public void setUnitPrice(double unitPrice)
 {
 this.unitPrice = unitPrice;
 } // end method setUnitPrice
 
// method to set the number of units in stock
 public void setUnitsInStock(double unitsInStock) 
{
 this.unitsAvailable = unitsInStock;
 } // end method setUnitsInStock
 
// method to set the item number
 public void setItemNumber(int itemNumber)
 {
 this.itemNumber = itemNumber;
 } // end method setItemNumber
 
// method to compare dvd title's in the inventory class
 public int compareTo( Object anotherProduct)
 {
 Product tmp = (Product) anotherProduct;
 
return this.getDvd().compareTo(tmp.getDvd());
 } // end method compareTo
 } // end class Product
 

ProductProducer.java file
 
package comparable.Inventory;
 
import javax.swing.ImageIcon;
 import javax.swing.JLabel;
 
public class ProductProducer extends Product
 {
 private String producer; // Producer of film
 
// five-argument constructor
 public ProductProducer( String dvd, String producer, int itemNumber, double unitsAvailable, double unitPrice)
 {
 super( dvd, itemNumber, unitsAvailable, unitPrice );
 setProducer(producer); // validates and stores producer
 } // end five-argument constructor
 
// set Producer
 public void setProducer( String producer )
 {
 this.producer = producer;
 } // end method setProducer
 
// method to get Producer
 public String getProducer()
 {
 return producer;
 } // end method getProducer
 
@Override // This method Overrides the getValue() method in its super class Product
 public double getValue()
 { 
// this statement returns the value of the Product class getValue() function * 1.05 for re-stocking fee
 return super.getValue() * 1.05;
 } // end the Override getValue()
 } // end class ProductProducer
 

logo.java file
 
package comparable.Inventory; // uses package comparable.Inventory
 
import javax.swing.ImageIcon; // imports javax.swing's ImagIcon method
 import javax.swing.JLabel; // imports javax.swing's JLabel method
 
// declares class Logo
 public class Logo 
{
 // Declares method logo to display the image.png picture
 public JLabel logo()
 { 
// creates ImageIcon for image.png in bin folder
 ImageIcon image = new ImageIcon(getClass().getResource("image.png"));
 
// Creates new JLabel and fills it with image.png
 JLabel picture = new JLabel(image);
 return (picture); // returns picture as a JLabel
 } // end method logo
 } // end class Logo 


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1