Code:
import java.awt.*; // This is real important for the GUI interface....it contains all the classes for creating
//user interfaces and for painting graphics and images.
// good example for showing an image http://www.roseindia.net/java/example/java/awt/AwtImage.shtml
import javax.swing.*; // Allows for the creation of Swing text components with this you can display text and optionally
// allow the user to edit the text...which will be a benefit to us in editing fields in the
// next part.
import java.io.InputStreamReader; // Class to be able to read bytes and convert them into characters
// a good example would be on web page http://www.codeproject.com/KB/java/javabasicsio.aspx
import java.io.IOException; // Class to be able to construct i/o exceptions with a specified cause and detail messages
// good example at http://www.roseindia.net/java/beginners/WriteTextFileExample.shtml
import java.util.*; // The contains collections of framework, legacy collection classes, event model,
// date and time facilities, and miscellaneous utility classes to allow you to reuse code
// for things such as arrays, string tokenizer and random-number generation
import java.text.NumberFormat; // Class that allows for the easy formating of number with such methods as getCurrencyInstance
import java.io.BufferedReader; // Class to be able to read text from a character-input stream
// it buffer characters so as to provide for the efficient reading of character
// arrays and lines...general used with FileReaders adn InputStreamReaders
import java.awt.event.*;
import java.net.URL;
/* The first thing to define here is a class to hold the information for a product.
Notice there is no "public" interface to this class. If we used the word "public"
in front then this class would have to be in a file of its own. Product can only
be used within this program. Additionally notice the word Comparable, that is coming from using
java.util.* collections and will allow us to use sort without defining our own method */
class Product implements Comparable
{ //Remember private variables can only be read locally.
private double prodprice; //Product price
private int numinstock; //Number of product in stock
private String prodname; //Name of the product
private int prodId; //Product id number.
public Product() // Default constructor for the Product
{ // Left blank intentionally....number variables already set to 0 automatically.
}
// Constructor
public Product(int In_ProductNumber, double In_ProductPrice, int In_NumberInStock, String In_ProductName) {
this.prodId = In_ProductNumber;
this.prodprice = In_ProductPrice;
this.numinstock = In_NumberInStock;
this.prodname = In_ProductName;
}
public void set_prodId(int num) // Method to set the Product number
{
prodId = num;
}
public int get_prodId() // Method to get the Product number
{
return prodId;
}
public void set_prodprice(double prod) // Method to set the Price of the product
{
prodprice = prod;
}
public double get_prodprice() // Method to get the Price of the product
{
return prodprice;
}
public void set_numinstock(int numstock) // Method to set the Price of the product
{
numinstock = numstock;
}
public int get_numinstock() // Method to get the Price of the product
{
return numinstock;
}
public void set_prodname(String name) // Method to set the name of the product
{
prodname = name;
}
public String get_prodname() // Method to get the name of the product
{
return prodname;
}
public double calculateValue() // Method to calculate the value of the product inventory
{
return prodprice * numinstock;
}
//Before we created our own sort algorithm and did comparison using string compares.
//There is an easier way using code that is already provided by java called the
//the compareTo method. It is used to implement the Comparable interface which
//allows us to sort an array of Products using Arrays.sort()
//We can define it to compare any part of the array, in this case prodname.
//The trick to this method is that it returns -1, 0, or 1
//depending on if the compared to object should appear before, the same, or after
//the current item.
public int compareTo (Object o)
{
Product p = (Product) o;
return prodname.compareTo(p.get_prodname());
}
// We have been using this to print to the command line and now we
// will use it for error checking when having problems.
// Could have used the values straight out but decided to use the get methods instead.
public String toString()
{
return "Product Number : " + get_prodId() + "\n"
+ "Product Name : " + get_prodname() + "\n"
+ "Number in Stock : " + get_numinstock() + "\n"
+ "Product Price : " + NumberFormat.getCurrencyInstance(Locale.US).format(get_prodprice()) + "\n"
+ "Value : " + NumberFormat.getCurrencyInstance(Locale.US).format(calculateValue());
}
}//end class Product
// Extending the Product Class and to include Bulkproduct
class Bulkproduct extends Product
{ // New attribute of items per carton
private int p_itemsPerCarton;
public Bulkproduct () {
super();
}
//--------Constructor based on product as superclass
public Bulkproduct (int In_ProductNumber, double In_ProductPrice, int In_NumberInStock, String In_ProductName, int in_itemsPerCarton)
{
super(In_ProductNumber, In_ProductPrice, In_NumberInStock, In_ProductName);
p_itemsPerCarton=in_itemsPerCarton;
}
// method calculateValue() returns double of current value
// of unit count with addition 5% restock fee.
public double calculateValue() { return super.calculateValue()*1.05; }
public double get_restockingfee() { return super.get_prodprice()*1.05; }
public int get_itemsPerCarton() { return p_itemsPerCarton; };
public void set_itemsPerCarton( int in_itemsPerCarton ) { if ( in_itemsPerCarton<0 ) p_itemsPerCarton=0-in_itemsPerCarton;
else
p_itemsPerCarton=in_itemsPerCarton;
}
//---------toString method that extends the product toString
public String toString()
{
//---------The call to the super toString allows the capture of the private variables
//----------without having to call the get...methods
return String.format(super.toString()+String.format("\n%s: %d\n",
"Items/Carton",p_itemsPerCarton));
}
}//end clas Bulkproduct
// Class that represents a collection of Bulkproduct objects
class Inventory {
Bulkproduct[] myInventory; // An array of bulk products calling it myInventory
// create an initially empty inventory capable of holding different Bulkproducts
public Inventory( )
{
myInventory = new Bulkproduct[0];
}
// This is an interesting method so that the length of our array
// can in essence be dynamic. It will allow us add a Bulkproduct
// to the end of the inventory. For Part 6 we will need to figure out
// how to do a deleteBulkproduct.
public void setProduct(Product p, int index)
{
inventory[index] = p;
}
public void addBulkproduct(Bulkproduct new_Bulkproduct)
{
// create a new array of Bulkproducts that can hold one more than the current array of Bulkproducts
Bulkproduct[] new_inventory = new Bulkproduct[this.getSize() + 1];
//copy all the old ones to the front of the new array
for (int i = 0; i < this.getSize(); i++) {
new_inventory[i] = myInventory[i];
}
// add the new Bulkproduct to the end of the new array
new_inventory[this.getSize()] = new_Bulkproduct;
// replace the old inventory with the new one
myInventory = new_inventory;
}
// Get the number of Bulkproducts in the inventory
public int getSize()
{
return myInventory.length; //Another feature we have using the java.util.* collections
}
// Get the Bulkproducts at the location index in the inventory
public Bulkproduct getBulkproduct(int index)
{
return myInventory[index];
}
// Add up the value of all products in the array.
public double getTotalValueOfAllInventory()
{
double tot = 0.00;
for(int i = 0; i < getSize(); i++)
{
tot += myInventory[i].calculateValue();
}
return tot;
}
// Well now we are sorting the values in the myInventory
public void sortInventory()
{
Arrays.sort(myInventory);
}
}
// GUI for the Inventory
// Contains an inventory of product
// and lets the user step through them one by one
class InventoryGUI extends JFrame
{
// create inventory for the Office Supplies
private Inventory theInventory;
// index in the inventory of the currently displayed office supply.
// the index starts at 0, goes to the number of Office Supplies in the inventory minus 1
private int index = 0;
// GUI elements to display currently selected Office Supply's information
private final JLabel prodIdLabel = new JLabel("Item Number: ");
private JTextField prodIdText;
private final JLabel prodnameLabel = new JLabel("Product Name: ");
private JTextField prodnameText;
private final JLabel manufacturerLabel = new JLabel("Product Manufacturer: ");
private JTextField itemsPerCartonText;
private final JLabel prodpriceLabel = new JLabel("Price: ");
private JTextField prodpriceText;
private final JLabel numinstockLabel = new JLabel("Number in Stock: ");
private JTextField numinstockText;
private final JLabel valueLabel = new JLabel("Value: ");
private JTextField valueText;
private final JLabel restockingFeeLabel = new JLabel("Restocking Fee: ");
private JTextField restockingFeeText;
private final JLabel totalValueLabel = new JLabel("Inventory Total Value: ");
private JLabel totalValueText;
// setup the buttons in the GUI
// go to the next product in the list
private Action nextAction = new AbstractAction("Next")
{
public void actionPerformed(ActionEvent evt) {
// go forward one product
index++;
// check to see if there is a next product
if ( index == theInventory.getSize() ) {
// if we're at the last product in the list, then we can't go any further forward
// so we wrap around to the beginning
index = 0;
}
repaint();
}
};
private JButton nextButton = new JButton(nextAction);
// go the previous product in the list
private Action previousAction = new AbstractAction("Previous") {
public void actionPerformed(ActionEvent evt) {
index--;
// if the user hits previous at the first product in the list, then loop back to the last product
if (index < 0) {
index = theInventory.getSize() - 1;
}
repaint();
}
};
private JButton previousButton = new JButton(previousAction);
// advance to the first product in the list
private Action firstAction = new AbstractAction("First") {
public void actionPerformed(ActionEvent evt) {
index = 0;
repaint();
}
};
private JButton firstButton = new JButton(firstAction);
// advance to the last product in the list
private Action lastAction = new AbstractAction("Last") {
public void actionPerformed(ActionEvent evt) {
index = theInventory.getSize() - 1;
repaint();
}
};
private JButton lastButton = new JButton(lastAction);
// advance to the add product in the list
private Action addAction = new AbstractAction("ADD") {
public void actionPerformed(ActionEvent evt) {
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 0, 0.00, 0, "", 0) );;
index = theInventory.getSize() - 1;
repaint();
}
};
private JButton addButton = new JButton(addAction);
// advance to the delete product in the list
private Action deleteAction = new AbstractAction("DELETE") {
public void actionPerformed(ActionEvent evt) {
index = 0;
repaint();
}
};
private JButton deleteButton = new JButton(deleteAction);
// advance to the modify product in the list
private Action modifyAction = new AbstractAction("MODIFY") {
public void actionPerformed(ActionEvent evt) {
if (modifyButton.getText().equals("Modify")) {
modifyButton.setText("Click to Modify!");
// make the fields of the current dvd editable
prodIdText.setEditable(true);
prodnameText.setEditable(true);
itemsPerCartonText.setEditable(true);
prodpriceText.setEditable(true);
numinstockText.setEditable(true);
// the second time,
} else if (modifyButton.getText().equals("Click to Modify!")) {
try {
//Assign the text fields to variables
String prodIdTemp = prodIdText.getText().trim();
//Convert text into int and double.
int prodNumTemp = Integer.parseInt ( prodIdTemp );
Product newProduct = new Product(prodNumTemp, prodnameTemp, itemsPerCartonTemp, prodpriceTemp, numinstockTemp );
ProductInventory2.setProduct(newProduct, index);
} catch (Exception modifyException) {
JOptionPane.showMessageDialog(null, "Error modifying dvd's information:\n" + modifyException);
}
modifyButton.setText("Modify");
prodIdTemp.setEditable(false);
// update the display
repaint();
}
};
private JButton modifyButton = new JButton(modifyAction);
// advance to the save product in the list
private Action saveAction = new AbstractAction("SAVE") {
public void actionPerformed(ActionEvent evt) {
prodIdText.getText().trim();
prodnameText.getText().trim();
itemsPerCartonText.getText().trim();
prodpriceText.getText().trim();
numinstockText.getText().trim();
repaint();
}
};
private JButton saveButton = new JButton(saveAction);
// Add the product to the underlying inventory object
public void addBulkproductToInventory(Bulkproduct temp)
{
theInventory.addBulkproduct(temp);
sortInventory();
repaint();
}
// sort the items in the underlying inventory object
public void sortInventory()
{
theInventory.sortInventory();
repaint();
}
// constructor for the GUI, in charge of creating all GUI elements
public InventoryGUI()
{
// create the inventory object that will hold the product information
theInventory = new Inventory();
// setup the GUI
// add the next button to the top of the GUI
// setup a panel to collect all the buttons in a GridLayout with 1 row and 4 columns
JPanel buttonPanel = new JPanel(new GridLayout(1, 4, 0, 4));
buttonPanel.add(firstButton);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
buttonPanel.add(lastButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JPanel buttonPanel2 = new JPanel(new GridLayout(4, 1, 4, 1));
buttonPanel2.add(addButton);
buttonPanel2.add(deleteButton);
buttonPanel2.add(modifyButton);
buttonPanel2.add(saveButton);
getContentPane().add(buttonPanel2, BorderLayout.EAST);
// product information
// setup a panel to collect all the components in a GridLayout with 8 rows and 2 columns.
JPanel centerPanel = new JPanel(new GridLayout(8, 2, 0, 4));
centerPanel.add(prodIdLabel);
prodIdLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodIdText = new JTextField("");
prodIdText.setEditable(false );
centerPanel.add(prodIdText);
centerPanel.add(prodnameLabel);
prodnameLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodnameText = new JTextField("");
prodnameText.setEditable(false);
centerPanel.add(prodnameText);
centerPanel.add(manufacturerLabel);
manufacturerLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
itemsPerCartonText = new JTextField("");
itemsPerCartonText.setEditable(false);
centerPanel.add(itemsPerCartonText);
centerPanel.add(prodpriceLabel);
prodpriceLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodpriceText = new JTextField("");
prodpriceText.setEditable(false);
centerPanel.add(prodpriceText);
centerPanel.add(numinstockLabel);
numinstockLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
numinstockText = new JTextField("");
numinstockText.setEditable(false);
centerPanel.add(numinstockText);
centerPanel.add(restockingFeeLabel);
restockingFeeLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
restockingFeeText = new JTextField("");
restockingFeeText.setEditable(false);
centerPanel.add(restockingFeeText);
centerPanel.add(valueLabel);
valueLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
valueText = new JTextField("");
valueText.setEditable(false);
centerPanel.add(valueText);
// add the overall inventory information to the panel
centerPanel.add(totalValueLabel);
totalValueLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
totalValueText = new JLabel("");
centerPanel.add(totalValueText);
// setup the logo for the GUI
URL url = this.getClass().getResource("logo.jpg");
Image img = Toolkit.getDefaultToolkit().getImage(url);
// scale the image so that it'll fit in the GUI
Image scaledImage = img.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING);
// create a JLabel with the image as the label's Icon
Icon logoIcon = new ImageIcon(scaledImage);
JLabel companyLogoLabel = new JLabel(logoIcon);
companyLogoLabel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
// add the logo to the GUI
getContentPane().add(companyLogoLabel, BorderLayout.WEST);
// add the panel to the center of the GUI's window
getContentPane().add(centerPanel, BorderLayout.CENTER);
}
// Get the GUI to show up on the screen
public void showGUI() {
this.setDefaultCloseOperation( EXIT_ON_CLOSE );
this.pack();
this.setSize(700, 400);
this.setResizable(false);
this.setLocationRelativeTo( null );
this.setVisible(true);
repaint();
}
// repaint the GUI with current product's information
public void repaint() {
Bulkproduct temp = theInventory.getBulkproduct(index);
if (temp != null) {
prodIdText.setText( ""+temp.get_prodId() );
prodnameText.setText( temp.get_prodname() );
itemsPerCartonText.setText( String.format("%d",temp.get_itemsPerCarton()));
prodpriceText.setText( String.format("$%.2f", temp.get_prodprice()) );
restockingFeeText.setText( String.format("$%.2f", temp.get_restockingfee()) );
numinstockText.setText( ""+temp.get_numinstock() );
valueText.setText( String.format("$%.2f", temp.calculateValue() ) );
}
totalValueText.setText( String.format("$%.2f", theInventory.getTotalValueOfAllInventory() ) );
}
} // End InventoryGUI class
// Program that displays the value of products in the inventory.
class InventoryPart5
{
public static void main( String args[] ) throws IOException
{
// create Scanner to obtain input from command window
BufferedReader input = new BufferedReader(new InputStreamReader(System.in) );
//Instantiate a GUI Inventory object
InventoryGUI myInventoryGUI = new InventoryGUI();
// change this to false to do command line input
if ( true ) { /* program not working when set to true for some reason */
System.out.println("Loading\n\n");
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 1, 9.99, 300, "DVD", 20) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 2, 3.99, 25, "ToothPaste", 15) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 3, 5.99, 33, "Candy Bar", 22) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 4, 10.99, 10, "Ink", 500) );
System.out.println("Done loading\n\n");
} else {
//Print out a screen title
System.out.println("Inventory Program\n\n");
// we're going to keep asking for user input until the user enters stop for an item name
while(true) {
//Instantiate a new Bulkproduct object each time we could get input from the user
Bulkproduct myItem = new Bulkproduct();
System.out.println( "Enter the name of product or the word stop: " ); // prompt for input
myItem.set_prodname(input.readLine());// read item name or stop
// if the user entered stop for the item name, then quit the loop
if ( myItem.get_prodname().equalsIgnoreCase("stop") ) {
break;
}
//Enter Item number
System.out.print( "Enter the Item number: " ); // prompt for input
int prodId = Integer.valueOf(input.readLine()).intValue();
myItem.set_prodId(prodId);// read item number
// while loop to repeat the entry of the item number until a positive value is entered
while (myItem.get_prodId()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Number:");
myItem.set_prodId(Integer.valueOf(input.readLine()).intValue()); // read Item number
}
// Enter Number of Items in Stock
System.out.print("Enter number of Items in Stock: ");
myItem.set_numinstock(Integer.valueOf(input.readLine()).intValue()); // read Number of Items in Stock
// while loop to repeat the entry of Items in stock until a positive value is entered
while (myItem.get_numinstock() <= 0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Number in Stock:");
myItem.set_numinstock(Integer.valueOf(input.readLine()).intValue()); // read Item number
}
// Enter price of the Item
System.out.print( "Enter the price of the item: " ); // prompt for input
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue()); // Read price of the Bulkproduct
// while loop to repeat the entry of Items in stock until a positive value is entered
while (myItem.get_prodprice()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Price:");
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue()); // read Item Price
}
// Enter Number of Items in a Package
System.out.print( "Enter the Items / Carton: " ); // prompt for input
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue());
// while loop to repeat the entry of items / carton until a postitive value is entered
while (myItem.get_prodprice()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Price;");
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue());// Read items / carton name of the Bulkproduct
}
System.out.println();
// add the newly created object to the existing inventory
myInventoryGUI.addBulkproductToInventory(myItem);
} // end while
}
// Display the inventory of Bulkproducts on the screen, one Bulkproduct at a time
myInventoryGUI.showGUI();
} // end method main
} // end class InventoryPart5