| | |
Help with Inventory part 6 program please!!
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Sep 2007
Posts: 2
Reputation:
Solved Threads: 0
I have a program i have been working on for my Java class and it is due by the end of this week. My problem is a few things...(1) I do not know how to set the actions on the buttons Save, Delete, Modify and Add. Also I was able to get the previous button to work, but it will only go as far as the first item instead of continuing on through the list. (2) I need to add a logo..have no clue how to do this. (3) I need it to be able to save to a C:/data.file and well do not know how to do that either. Any help on getting these things started would be greatly appreciated.
This is the final requirements i was given....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. An
item added to the inventory should have an item number one more than the previous last
item.
• 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 that product’s information in the
GUI.
This is the code i have done so far...
This is the final requirements i was given....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. An
item added to the inventory should have an item number one more than the previous last
item.
• 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 that product’s information in the
GUI.
This is the code i have done so far...
import java.util.Arrays; // program uses arrays
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; // Import the java swing package
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Inventory5 {
// main method begins execution of java application
public static void main(String[] args) {
System.out.println("\nCheckPoint: Inventory Part 5");
System.out.println("My DVD Collection\n");
Movie dvd = null;
Inventory inventory = new Inventory();
dvd = new Movie(1, "Live Free or Die Hard", 18, 19.99f, 2001);
System.out.println(dvd);
inventory.addMovie(dvd);
dvd = new Movie(2, "The Patriot", 14, 20.99f, 1998);
System.out.println(dvd);
inventory.addMovie(dvd);
dvd = new Movie(3, "Full Metal Jacket", 1, 21.99f, 1995);
System.out.println(dvd);
inventory.addMovie(dvd);
dvd = new Movie(4, "Coyote Ugly", 15, 18.99f, 2003);
inventory.addMovie(dvd);
System.out.println(dvd);
dvd = new Movie(5, "Apocalypto", 10, 21.99f, 2006);
System.out.println(dvd);
inventory.addMovie(dvd);
dvd = new Movie(6, "Monster in Law", 1, 7.99f, 2005);
System.out.println(dvd);
System.out.println("\nEnd of DVD collection!\n");
inventory.addMovie(dvd);
inventory.printInventory();
new InventoryGUI(inventory);
} // end main
} // end Inventory5
class DVD {
private int itemNo;
private String title;
private int inStock;
private float unitPrice;
DVD(int itemNo, String title, int inStock, float unitPrice) {
this.itemNo = itemNo;
this.title = title;
this.inStock = inStock;
this.unitPrice = unitPrice;
}
public int getItemNo() { return itemNo; }
public String getTitle() { return title; }
public int getInStock() { return inStock; }
public float getUnitPrice() { return unitPrice; }
public float value() {
return inStock * unitPrice;
}
public String toString() {
return String.format("itemNo=%2d title=%-22s inStock=%3d price=$%7.2f value=$%8.2f",
itemNo, title, inStock, unitPrice, value());
}
} // end DVD
class Inventory {
// Setup an array of Movies (set it to hold 30 items)
private final int INVENTORY_SIZE = 30;
private DVD[] items;
private int numItems;
Inventory() {
items = new Movie[INVENTORY_SIZE];
numItems = 0;
}
public int getNumItems() {
return numItems;
}
public DVD getDVD(int n) {
return items[n];
}
// Adds a Movie to the array of Movies. Adds to first empty slot found.
public void addMovie(DVD item) {
items[numItems] = item;
++numItems;
}
// Loop through our array of Movies and add up the total value.
// Go item by item adding the quantity on hand x its price.
// Add that value to a running total accumulator variable.
public double value() {
double sumOfInventory = 0.0;
for (int i = 0; i < numItems; i++)
sumOfInventory += items[i].value();
return sumOfInventory;
}
// Prints the inventory list including name, quantity, price,
// and total stock value for each item.
public void printInventory() {
System.out.println("\nShelly's DVD Inventory\n");
// If no items were found, print a message saying the inventory is empty.
if (numItems <= 0) {
System.out.println("Inventory is empty at the moment.\n");
} else {
for (int i = 0; i < numItems; i++)
System.out.printf("%3d %s\n", i, items[i]);
System.out.printf("\nTotal value in inventory is $%,.2f\n\n", value());
}
}
} // end Inventory
// Extends DVD class from the base class DVD
class Movie extends DVD {
// Holds movie year and adds restocking fee
private int movieYear;
// Constructor, calls the constructor of Movie first
public Movie(int MovieID, String itemName, int quantityOnHand, float itemPrice, int year) {
super(MovieID, itemName, quantityOnHand, itemPrice);
// Pass on the values needed for creating the Movie class first thing
this.movieYear = movieYear;
}
// To set the year manually
public void setYear(int year) {
movieYear = year;
}
// Get the year of this DVD Movie
public int getMovieYear() {
return movieYear;
}
// Overrides value() in Movie class by calling the base class version and
// adding a 5% restocking fee on top
public float value() {
return super.value() + restockingFee();
}
// Simply gets the base class's value, and figures out the 5% restocking fee only
public float restockingFee() {
return super.value() * 0.05f;
}
} // end Movie
// GUI for the Inventory
// Contains an inventory of DVD's and lets the user step through them one by one
class InventoryGUI extends JFrame
{
// access inventory for DVD Collection
private Inventory theInventory;
// index in the inventory of the currently displayed DVD.
// the index starts at 0, goes to the number of DVDs in the inventory minus 1
private int index = 0;
// GUI elements to display currently selected DVD information
private final JLabel itemNumberLabel = new JLabel(" Item Number:");
private JTextField itemNumberText;
private final JLabel prodnameLabel = new JLabel(" Product Name:");
private JTextField prodnameText;
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 JTextField totalValueText;
private JPanel centerPanel;
private JPanel buttonPanel;
// constructor for the GUI, in charge of creating all GUI elements
InventoryGUI(Inventory inventory) {
super("Shelly's Movie Inventory");
final Dimension dim = new Dimension(140, 20);
final FlowLayout flo = new FlowLayout(FlowLayout.LEFT);
JPanel jp;
// create the inventory object that will hold the product information
theInventory = inventory;
// setup the GUI
// product information
// setup a panel to collect all the components.
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
buttonPanel = new JPanel();
JButton firstButton = new JButton("First");
firstButton.addActionListener(new FirstButtonHandler());
buttonPanel.add(firstButton);
JButton previousButton = new JButton("Previous");
previousButton.addActionListener(new PreviousButtonHandler());
buttonPanel.add(previousButton);
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new NextButtonHandler());
buttonPanel.add(nextButton);
JButton lastButton = new JButton("Last");
lastButton.addActionListener(new LastButtonHandler());
buttonPanel.add(lastButton);
JButton addButton = new JButton("Add");
addButton.addActionListener(new AddButtonHandler());
buttonPanel.add(addButton);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(new DeleteButtonHandler());
buttonPanel.add(deleteButton);
JButton modifyButton = new JButton("Modify");
modifyButton.addActionListener(new ModifyButtonHandler());
buttonPanel.add(modifyButton);
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new SaveButtonHandler());
buttonPanel.add(saveButton);
JButton searchButton = new JButton("Search");
searchButton.addActionListener(new SearchButtonHandler());
buttonPanel.add(searchButton);
centerPanel.add(buttonPanel);
jp = new JPanel(flo);
itemNumberLabel.setPreferredSize(dim);
jp.add(itemNumberLabel);
itemNumberText = new JTextField(3);
itemNumberText.setEditable(false);
jp.add(itemNumberText);
centerPanel.add(jp);
jp = new JPanel(flo);
prodnameLabel.setPreferredSize(dim);
jp.add(prodnameLabel);
prodnameText = new JTextField(17);
prodnameText.setEditable(false);
jp.add(prodnameText);
centerPanel.add(jp);
jp = new JPanel(flo);
prodpriceLabel.setPreferredSize(dim);
jp.add(prodpriceLabel);
prodpriceText = new JTextField(17);
prodpriceText.setEditable(false);
jp.add(prodpriceText);
centerPanel.add(jp);
jp = new JPanel(flo);
numinstockLabel.setPreferredSize(dim);
jp.add(numinstockLabel);
numinstockText = new JTextField(5);
numinstockText.setEditable(false);
jp.add(numinstockText);
centerPanel.add(jp);
jp = new JPanel(flo);
restockingFeeLabel.setPreferredSize(dim);
jp.add(restockingFeeLabel);
restockingFeeText = new JTextField(17);
restockingFeeText.setEditable(false);
jp.add(restockingFeeText);
centerPanel.add(jp);
jp = new JPanel(flo);
valueLabel.setPreferredSize(dim);
jp.add(valueLabel);
valueText = new JTextField(17);
valueText.setEditable(false);
jp.add(valueText);
centerPanel.add(jp);
// add the overall inventory information to the panel
jp = new JPanel(flo);
totalValueLabel.setPreferredSize(dim);
jp.add(totalValueLabel);
totalValueText = new JTextField(17);
totalValueText.setEditable(false);
jp.add(totalValueText);
centerPanel.add(jp);
// add the panel to the GUI display
setContentPane(centerPanel);
repaintGUI();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(420, 480);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
// (re)display the GUI with current product's information
public void repaintGUI() {
Movie temp = (Movie) theInventory.getDVD(index);
if (temp != null) {
itemNumberText.setText("" + temp.getItemNo());
prodnameText.setText(temp.getTitle());
prodpriceText.setText(String.format("$%.2f", temp.getUnitPrice()));
restockingFeeText.setText(String.format("$%.2f", temp.restockingFee()));
numinstockText.setText("" + temp.getInStock());
valueText.setText(String.format("$%.2f", temp.value()));
}
totalValueText.setText(String.format("$%.2f", theInventory.value()));
}
class FirstButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
index = 0;
repaintGUI();
}
}
class PreviousButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
int numItems = theInventory.getNumItems();
index = (--index) % numItems;
repaintGUI();
}
}
class NextButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int numItems = theInventory.getNumItems();
index = (++index) % numItems;
repaintGUI();
}
}
class LastButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
int numItems = theInventory.getNumItems();
index = (numItems -1) % numItems;
repaintGUI();
}
}
class AddButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
repaintGUI();
}
}
class SaveButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
repaintGUI();
}
}
class ModifyButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
repaintGUI();
}
}
class DeleteButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
repaintGUI();
}
}
class SearchButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e){
repaintGUI();
}
}
} // End InventoryGUI class Try to write a class that saves the objects you create (namely the Inventory instance that has all the DVDs and movies) to a file. Yo could use the classes:
FileInputStream
ObjectInputStream
FileOutputStream
ObjectOutputStream
You objects must also implement the Serializable interface to do that
FileInputStream
ObjectInputStream
FileOutputStream
ObjectOutputStream
You objects must also implement the Serializable interface to do that
Check out my New Bike at my Public Profile at the "About Me" tab
For your previous button, I think you want to do something like
This will allow you to cycle through your inventory items by pressing the Previous button when you are at the first item. You can do the opposite with the Next button to cycle through when you hit Next at the last item in the list.
For your logo, I think you will need to use the java.awt.image package.
java Syntax (Toggle Plain Text)
index--; if (index < 0) { index = numItems - 1; }
This will allow you to cycle through your inventory items by pressing the Previous button when you are at the first item. You can do the opposite with the Next button to cycle through when you hit Next at the last item in the list.
For your logo, I think you will need to use the java.awt.image package.
There are no stupid questions, only those too stupid to ask for help.
echo is a web developer's best friend. •
•
Join Date: Feb 2008
Posts: 18
Reputation:
Solved Threads: 0
I noticed no one ever posts their answers. I used the basics from this persons program to do mine - I really liked the way they went about it... So I decided to post my final project finished - everything works - I am sure the java geniuses are going to tell me it is all wrong - I had to use my own logic in some places but I am really proud of it so here it is - I combined all the files into one but obviously you could split them up.
// cleverly programmed by make it work productions
import java.awt.*; // import the java awt package
import java.awt.event.*; // Import the java event package
import javax.swing.*; // Import the java swing package
import java.util.*; // Import the java utility package
import java.io.*; // Import the java input output package
import java.lang.*; // Import the java lang package
import java.text.*; // Import the java text package
import java.math.*; // Import the java math package
// starts the program sets up the intial inventory
public class CdInvApp {
// main method begins execution of java application
public static void main(String[] args) {
FeeQtyProduct product = null;
CdInv inventory = new CdInv();
product = new FeeQtyProduct( "Godsmack",1, 12, 12.95, "Alive" );
inventory.addFeeQtyProduct(product );
product = new FeeQtyProduct( "Aerosmith", 2, 8, 8.95, "Big Ones" );
inventory.addFeeQtyProduct(product );
product = new FeeQtyProduct( "Nelsen Adelard", 3, 4, 10.95, "Take Me Back");
inventory.addFeeQtyProduct(product );
product = new FeeQtyProduct( "Union Underground", 4, 7, 11.95, "Mr.Deadman" );
inventory.addFeeQtyProduct(product );
new CdInvGUI(inventory); // open GUI
} // end main
} // end CdInvApp
abstract class Product
{
public String productName; //name
public int productNumber; // product number
private double baseAmount; // quantity in Inv
private double basePrice; // inital price
// four-argument constructor
public Product( String name, int number, double amount, double price )
{
productName = name;
productNumber = number;
baseAmount = amount;
basePrice = price;
} // end four-argument Product constructor
// set Product Name
public void setProductName( String name )
{
productName = name;
} // end method setProductName
// return ProductName
public String getProductName()
{
return productName;
} // end method getProductName
// set ProductNumber
public void setProductNumber( int number )
{
productNumber = number; // should validate
} // end method setProductNumber
// return ProductNumber
public int getProductNumber()
{
return productNumber;
} // end method getProductNumber
// set initial price
public void setBaseAmount( double amount )
{
baseAmount = amount;
} // end method setBaseAmount
// return BaseAmount
public double getBaseAmount()
{
return baseAmount;
} // end method getBaseAmount
// set BasePrice
public void setBasePrice( double price )
{
basePrice = price; // non-negative
} // end method setBasePrice
// return BasePrice
public double getBasePrice()
{
return basePrice;
} // end method getBasePrice
// return String representation of Product object no longer needed
public String toString()
{
return String.format( "%s\nProduct#: %f\nQTY#:%.0f\nPrice: $%.2f ",
getProductName(), getProductNumber(), getBaseAmount(), getBasePrice() );
} // end method toString
// abstract method overridden by subclasses
public abstract double total(); // no implementation here
public abstract double restock(); // no implementation here
} // end abstract class Product
class FeeQtyProduct extends Product
{
private String albumTitle; // album title
// five-argument constructor
public FeeQtyProduct( String name, int number, double amount, double price, String title )
{
super( name, number, amount, price );
setAlbumTitle( title);
} // end five-argument FeeQtyProduct constructor
// set AlbumTitle
public void setAlbumTitle( String title )
{
albumTitle = title;
} // end method setAlbumTitle
// return AlbumTitle
public String getAlbumTitle()
{
return albumTitle;
} // end method getAlbumTitle
// calculate total; override method total in Product
public double total()
{
return getBasePrice() * getBaseAmount();
} // end method total
// calculate earnings; override method total in QtyProduct
public double restock()
{
return getBasePrice() * 1.05;
} // end method restock
// return String representation of FeeQtyProduct object no longer needed
public String toString()
{
return String.format( "%s: %s\n%s: %s",
"Artist", super.toString(),
"Album", getAlbumTitle());
} // end method toString
} // end class FeeQtyProduct
// create inventory list
class CdInv
{
// delare variables
public static final int INVENTORY_SIZE = 30;
private FeeQtyProduct[] items;
public int numItems;
CdInv() //sets the number of items
{
items = new FeeQtyProduct[INVENTORY_SIZE];
numItems = 0;
}
//returns number of items
public int getNumItems()
{
return numItems;
}
//returns each product
public FeeQtyProduct getFeeQtyProduct(int i)
{
return items[i];
}
//deletes item and recounts number of items
public void remove(int i)
{
items[i] = items[numItems -1];
--numItems;
}
//adds products to the inventory
public void addFeeQtyProduct( FeeQtyProduct item)
{
items[numItems] = item;
++numItems;
}
// reduces numbers of items in inventory
public void removeFeeQtyProduct(FeeQtyProduct item)
{
items[numItems] = item;
--numItems;
}
// returns the amount one item inventory is worth
public double value()
{
double sum = 0.0;
for (int i = 0; i < numItems; i++)
sum += items[i].total();
return sum;
}// end double value
} // end CdInv
// draw company logo
class ArcsJPanel extends JPanel
{
public void paintComponent( Graphics g )
{
super.paintComponent( g ); // call superclass's paintComponent
// draws larger 3d rectangle
g.setColor( Color.RED );
g.draw3DRect( 45, 15, 180, 40, true);
// draws small black square
g.setColor( Color.BLACK );
g.draw3DRect( 5, 15, 40, 40, true );
g.fill3DRect( 5, 15, 40, 40, false );
//draws circle
g.setColor( Color.RED );
g.drawArc( 5, 15, 40, 40, 10, 360 );
//fills circle
g.setColor( Color.WHITE);
g.fillArc( 5, 15, 40, 40, 10, 360 );
// draws company name
g.setColor( Color.BLACK );
g.setFont( new Font( "Serif", Font.BOLD, 25 ) );
g.drawString( "BS MUSIC INC.", 10, 45 );
} // end method paintComponent
} // end class ArcsJPanel
// GUI for the Inventory
class CdInvGUI extends JFrame
{
private CdInv myCdInv;
public int index = 0;
// GUI elements to display information
private final JLabel itemNumberLabel = new JLabel(" Item Number:");
public JTextField itemNumberText;
private final JLabel artistLabel = new JLabel( "Artist:");
private JTextField artistText;
private final JLabel albumLabel = new JLabel("Album:");
private JTextField albumText;
private final JLabel priceLabel = new JLabel(" Price: $");
private JTextField priceText;
private final JLabel qtyLabel = new JLabel(" Quantity:");
private JTextField qtyText;
private final JLabel valueLabel = new JLabel(" Value:");
private JTextField valueText;
private final JLabel restockFeeLabel = new JLabel(" with Restock Fee:");
private JTextField restockFeeText;
private final JLabel totalValueLabel = new JLabel(" Inventory Total Value:");
private JTextField totalValueText;
private final JLabel searchLabel = new JLabel("Search:");
private JTextField searchText;
// constructor for the GUI, in charge of creating all GUI elements
CdInvGUI(CdInv inventory)
{
ArcsJPanel arcsJPanel = new ArcsJPanel(); // create ArcsJPanel
final Dimension size = new Dimension(125,20);
final Dimension size2 = new Dimension(300,60);
final FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
JPanel jpanel = new JPanel();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2, 4));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
// create the inventory object that will hold the product information
myCdInv = inventory;
// setup the GUI
// product information
// setup a panel to collect all the components.
JButton firstButton = new JButton("First");
buttonPanel.add(firstButton);
JButton previousButton = new JButton("Previous");
buttonPanel.add(previousButton);
JButton nextButton = new JButton("Next");
buttonPanel.add(nextButton);
JButton lastButton = new JButton("Last");
buttonPanel.add(lastButton);
JButton addButton = new JButton("Add");
buttonPanel.add(addButton);
JButton deleteButton = new JButton("Delete");
buttonPanel.add(deleteButton);
JButton modifyButton = new JButton("Modify");
buttonPanel.add(modifyButton);
JButton saveButton = new JButton("Save");
buttonPanel.add(saveButton);
JButton searchButton = new JButton("Search");
buttonPanel.add(searchButton);
JButton helpButton = new JButton("help");
buttonPanel.add(helpButton);
// start JPanel layout
jpanel = new JPanel(layout);
arcsJPanel.setPreferredSize(size2);
jpanel.add(arcsJPanel);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
itemNumberLabel.setPreferredSize(size);
jpanel.add(itemNumberLabel);
itemNumberText = new JTextField(3);
itemNumberText.setEditable(false);
jpanel.add(itemNumberText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
artistLabel.setPreferredSize(size);
jpanel.add(artistLabel);
artistText = new JTextField(10);
artistText.setEditable(true);
jpanel.add(artistText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
albumLabel.setPreferredSize(size);
jpanel.add(albumLabel);
albumText = new JTextField(10);
albumText.setEditable(true);
jpanel.add(albumText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
priceLabel.setPreferredSize(size);
jpanel.add(priceLabel);
priceText = new JTextField(10);
priceText.setEditable(true);
jpanel.add(priceText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
qtyLabel.setPreferredSize(size);
jpanel.add(qtyLabel);
qtyText = new JTextField(5);
qtyText.setEditable(true);
jpanel.add(qtyText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
restockFeeLabel.setPreferredSize(size);
jpanel.add(restockFeeLabel);
restockFeeText = new JTextField(5);
restockFeeText.setEditable(false);
jpanel.add(restockFeeText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
valueLabel.setPreferredSize(size);
jpanel.add(valueLabel);
valueText = new JTextField(5);
valueText.setEditable(false);
jpanel.add(valueText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
totalValueLabel.setPreferredSize(size);
jpanel.add(totalValueLabel);
totalValueText = new JTextField(5);
totalValueText.setEditable(false);
jpanel.add(totalValueText);
centerPanel.add(jpanel);
jpanel = new JPanel(layout);
searchLabel.setPreferredSize(size);
jpanel.add(searchLabel);
searchText = new JTextField(10);
searchText.setEditable(true);
jpanel.add(searchText);
centerPanel.add(jpanel);
JFrame frame = new JFrame("Greatest Inventory Program of All Time"); // JFrame container
frame.setLayout(new BorderLayout()); // set layout
frame.add(buttonPanel, BorderLayout.SOUTH); // adds buttons to frame
frame.add(centerPanel, BorderLayout.CENTER); // adds center panel to frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // terminate upon close
frame.setSize(375, 425); // set size
frame.setResizable(true);
frame.setLocationRelativeTo(null); // set location
frame.setVisible(true); // display the window
repaintGUI();
// start inner classes to add actions to buttons
firstButton.addActionListener(new ActionListener() //goes to first entry
{
public void actionPerformed(ActionEvent e)
{
index = 0;
repaintGUI();
}// end action
});// end class
previousButton.addActionListener(new ActionListener() //allows user to add entry
{
public void actionPerformed(ActionEvent e)
{
int numItems = myCdInv.getNumItems();
if (numItems != 0)
index = (--index) % numItems;
if (index < 0)
index = numItems - 1;
if (numItems == 0) // catches for last entry not needed because we add a blank entry at zero but just in case
JOptionPane.showMessageDialog(null, "That's the last entry.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
repaintGUI();
}// end action
}); // end class
nextButton.addActionListener(new ActionListener() //goes to next entry on the list
{
public void actionPerformed(ActionEvent e)
{
int numItems = myCdInv.getNumItems();
index = (++index) % numItems; // moves index up one
repaintGUI();
}// end action
}); // end class
lastButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int numItems = myCdInv.getNumItems();
index = (numItems -1) % numItems; //goes to first entry then minus one
repaintGUI();
}// end action
}); // end clas
addButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
FeeQtyProduct temp = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
int numItems = myCdInv.getNumItems() +1;
index = (numItems - 2) % numItems;
repaintGUI();
if(artistText.getText().equals("Add Artist Name" )) // catches for assigning more then one blank at a time
{
JOptionPane.showMessageDialog(null, "Please fill out the blank entry you already have before adding more\nRemember: Push Modify when you finish with your changes","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
}
if(artistText.getText().equals("Add Artist Name" ) !=true) // allows the adding of an entry
{
FeeQtyProduct product = new FeeQtyProduct( "Add Artist Name", Integer.parseInt(itemNumberText.getText()) + 1, 0, 0.0, "Add Album Title");
index = (numItems - 1) % numItems;
myCdInv.addFeeQtyProduct(product );
repaintGUI();
}
if (numItems == 29) // catches for going over static inventory size
{
myCdInv.removeFeeQtyProduct(temp);
JOptionPane.showMessageDialog(null, "Please No More Entries\n You can increase my capacity in the java file CdInvApp.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
}
}// end action
}); // end class
saveButton.addActionListener(new ActionListener() // saves the dat file in English
{
public void actionPerformed(ActionEvent e)
{
int numItems = myCdInv.getNumItems();
InventoryStorage record = new InventoryStorage(); //calls inventroy storage class
record.openFile();
int currentRecord = 0; // keeps track of number of cycles
do // cycles through the list adding them one at a time
{
record.addRecords();
currentRecord = currentRecord + 1;
index = (++index) % numItems;
} while (currentRecord < numItems); //ends while
record.closeFile(); //closes file
}//end action
}); // end class
modifyButton.addActionListener(new ActionListener() // saves changes to the GUI
{
public void actionPerformed(ActionEvent e)
{
if (artistText.getText().equals("")) //traps for blank entry
{
JOptionPane.showMessageDialog(null, "Please Complete the Entry.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
repaintGUI();
}
if (albumText.getText().equals("")) //traps for blank entry
{
JOptionPane.showMessageDialog(null, "Please Complete the Entry.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
repaintGUI();
}
try // traps for letters and blank entry
{
Double.parseDouble(qtyText.getText());
Double.parseDouble(priceText.getText());
}
catch (Exception d)
{
JOptionPane.showMessageDialog(null, "Recheck Entry use numbers for price and quantity.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
repaintGUI();
}
String name; int number; double amount, price; String title; // declares variables
name = artistText.getText();
number = Integer.parseInt(itemNumberText.getText());
amount = Double.parseDouble(qtyText.getText());
price = Double.parseDouble(priceText.getText());
title = albumText.getText();
FeeQtyProduct modify = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
modify.setProductNumber(number);
modify.setProductName(name);
modify.setBaseAmount(amount);
modify.setBasePrice(price);
modify.setAlbumTitle(title);
repaintGUI();
}
}); // end class
deleteButton.addActionListener(new ActionListener() //allows user to delete entry and sorts product numbers to be in sequence
{
public void actionPerformed(ActionEvent e)
{
int numItems = myCdInv.getNumItems();
FeeQtyProduct temp = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
if (numItems != 0)
{
if(Integer.parseInt(itemNumberText.getText()) != numItems)
{
myCdInv.remove(index);
repaintGUI();
int i = Integer.parseInt(itemNumberText.getText());
index = (++index) % numItems;
repaintGUI();
int j = Integer.parseInt(itemNumberText.getText());
if (i > j)// my own little sort mechanism to keep Product numbers in sequence
index = (-- index) % numItems;
repaintGUI();
temp = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
temp.setProductNumber(j-1);
index = (++index) % numItems;
repaintGUI();
}// end if
if(Integer.parseInt(itemNumberText.getText()) == numItems) // uses a different method to remove entry if it is the last one prevents blank entry from being in the mix
{
myCdInv.removeFeeQtyProduct(temp);
index = (++index) % numItems;
repaintGUI();
}//end if
}// end if
if (numItems == 1) // catches for 0 items error
{
FeeQtyProduct product = new FeeQtyProduct( "Add Artist Name",numItems, 0, 0.0, "Add Album Title");
myCdInv.addFeeQtyProduct(product);
JOptionPane.showMessageDialog(null, "Delete Process Complete.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
repaintGUI();
} //end if
}// end action
}); // end class
searchButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//declare variables and gets text from GUI
String search = searchText.getText();
String name = artistText.getText();
int number = Integer.parseInt(itemNumberText.getText());
int numItems = myCdInv.getNumItems();
int currentRecord = 0;
do // gets text and checks for a match
{
index = (++index) % numItems;
repaintGUI();
name = artistText.getText();
number = Integer.parseInt(itemNumberText.getText());
search = searchText.getText();
currentRecord = (++currentRecord);
if(name.equalsIgnoreCase( search )) // stops on item
repaintGUI();
if(searchText.getText().equals("" )) //catches for no entry in the search box
{
JOptionPane.showMessageDialog(null, "You wanna search for nothing?","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
index = (--index) % numItems;
break;
}
if(currentRecord == numItems +1) // displays message if no results match search
{
JOptionPane.showMessageDialog(null, "No Results Found","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
break;
}
}while(name.equalsIgnoreCase(search ) != true); //ends do while
}//end action
}); // end class
helpButton.addActionListener(new ActionListener() // this is basically to tell you what to do with the program
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "FIRST Brings you to the first entry\nPREVIOUS Brings you to the last entry\nNEXT Brings you to the next entry\nLAST Brings you to the last entry\nADD adds a blank entry to allow a new listing see (MODIFY)\nSAVE Exports the entry's to a DAT file\nSEARCH allows you to search by product name\nMODIFY must be pressed to save changes within the GUI\nDELETE deletes the entry\nHELP you are in help\n","HELP", JOptionPane.PLAIN_MESSAGE);
repaintGUI();
}
}); // end class
} // end CdInvGUI
class InventoryStorage // creates the output file
{
private Formatter output; // object used to output text to file
public void openFile()
{
try
{
String strDirectoy ="C://data/";
// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success)
{
JOptionPane.showMessageDialog(null, "we had to create a directory named data in your C drive.","That's affirmative", JOptionPane.PLAIN_MESSAGE);
} //end if
}//end try
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "You do not have write access to the C: drive.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
}//end catch
try
{
output = new Formatter( "C:/data/inventory.dat");
} // end try
catch ( SecurityException securityException ) //catches for write access and exits program
{
JOptionPane.showMessageDialog(null, "You do not have write access to this file.","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
System.exit( 1 );
} // end catch
catch ( FileNotFoundException filesNotFoundException ) //catches for write access and exits program
{
JOptionPane.showMessageDialog(null, "Please create a file named data in your c drive","Negative GhostRider the pattern is full", JOptionPane.ERROR_MESSAGE);
System.exit( 1 );
} // end catch
JOptionPane.showMessageDialog(null, "file saved successfully.","That's affirmative", JOptionPane.PLAIN_MESSAGE);
} // end method openFile
public void addRecords() // adds the records to the file
{
FeeQtyProduct record = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
// rounds the output numbers to 2 decimals
BigDecimal roundPrice = new BigDecimal(Double.toString(record.restock() ));
roundPrice = roundPrice.setScale(2, RoundingMode.HALF_UP);
BigDecimal roundValue= new BigDecimal(Double.toString(record.total()));
roundValue= roundValue.setScale(2, RoundingMode.HALF_UP);
BigDecimal roundTotal= new BigDecimal(Double.toString(myCdInv.value()));
roundTotal = roundTotal.setScale(2, RoundingMode.HALF_UP);
if (record != null) //catches for blank record - overkill because we can never have a blank record
{
output.format( "Artist:%s Product#: %s QTY#:%.0f Price: $%.2f%s: %s" ,
record.getProductName(), record.getProductNumber(), record.getBaseAmount(), record.getBasePrice() ,
" Album", record.getAlbumTitle() + " with restock Fee $" + (roundPrice) + " value: $" + (roundValue) + " Inventory Total $" + (roundTotal) + "\t\n END OF LINE\t\t");
} // end if
} // end addRecords
public void closeFile() // close the file
{
if ( output != null )
output.close();
} // end method closeFile
}// end InventoryStorage class
// display GUI
public void repaintGUI()
{
FeeQtyProduct temp = (FeeQtyProduct) myCdInv.getFeeQtyProduct(index);
if(temp != null) //catches for no entries
{
itemNumberText.setText("" + temp.getProductNumber());
artistText.setText(temp.getProductName());
albumText.setText(String.format("%s", temp.getAlbumTitle()));
priceText.setText(String.format("%.2f", temp.getBasePrice()));
restockFeeText.setText(String.format("$%.2f", temp.restock()));
qtyText.setText(String.format("%.0f",temp.getBaseAmount()));
valueText.setText(String.format("$%.2f", temp.total()));
}// end if
totalValueText.setText(String.format("$%.2f", myCdInv.value()));
} // end repaintGUI
} // End InventoryGUI class Hi Midget,
If it works then it isn't wrong
However, I should point out that it's not the best idea to post your finished version. Anyone could just come along and copy your code. Here at Daniweb we try to guide people to a solution that they have found themselves rather than blurting out the answer. Please consider that next time.
If it works then it isn't wrong
However, I should point out that it's not the best idea to post your finished version. Anyone could just come along and copy your code. Here at Daniweb we try to guide people to a solution that they have found themselves rather than blurting out the answer. Please consider that next time. There are no stupid questions, only those too stupid to ask for help.
echo is a web developer's best friend. •
•
Join Date: Feb 2008
Posts: 18
Reputation:
Solved Threads: 0
They all compile and they all work - I have it set up as one file - you can change it if you'd like but you need to make the appropriate changes to the file name. If you were more specific about your problem - insted of "it doesn't work" - I could be
![]() |
Similar Threads
- Need help C++ inventory project (C++)
- Inventory program part 5 help (Java)
- Inventory part 6 (Java)
- Inventory part 5 (Java)
- GUI buttons Inventory Part 5 (Java)
- First Attempt at Arrays (Java)
- Inventory administration program (C)
Other Threads in the Java Forum
- Previous Thread: Problem creating factorize method for generating Prime Numbers
- Next Thread: I need help about a String Calculator
| Thread Tools | Search this Thread |
android api applet application array arrays automation awt bidirectional binary birt bluetooth businessintelligence busy_handler(null) chat class classes client code columns component constructor database designadrawingapplicationusingjavajslider draw eclipse editor error errors event eventlistener exception expand fractal game givemetehcodez graphics gui guidancer html ide image inetaddress input integer intellij j2me java javafx javamicroeditionuseofmotionsensor javaprojects jme jni jpanel jtree julia linux list loop map method methods mobile mobiledevelopmentcreatejar myaggfun netbeans newbie oracle parsing plazmic print problem program programming project recursion scanner screen server set sharepoint size smart sms smsspam sort sortedmaps sql string subclass support swing textfield threads time tree unlimited utility webservices windows






