Results 1 to 7 of 7
  1. #1
    ljk8950 is offline Member
    Join Date
    Jul 2008
    Posts
    43
    Rep Power
    0

    Default Functionality of Buttons

    I am hoping someone can help me with this. I have to add an "Add", "Delete", "Modify", "Save", and "Search" buttons to the below inventory program. I have been able to add all of these buttons to the program. In addition, I have been able to get the "Add" button to function. However, I am having trouble getting the "Delete", "Modify", "Save", and "Search" buttons to function. Thanks for any help you can give me!

    Java Code:
    // CheckPoint:  InventoryProgramPart6.java
    // Week 9
    // This program calculates inventory value
    
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    
    class Product implements Comparable
    {
         String name; // class variable that stores the item name
         double number; // class variable that stores the item number
         long stockQuantity; // class variable that stores the quantity in stock
         double price; // class variable that stores the item price
         double totalValue;
         public Product()
         {
              name = "";
              number = 0;
              stockQuantity = 0L;
              price = 0.0;
         }
    
         public Product(String name, int number, long stockQuantity, double price)
         {
              this.name = name;
              this.number = number;
              this.stockQuantity = stockQuantity;
              this.price = price;
         }
         
         public void setItemName(String name)
         {
              this.name = name;
         }
    
         public String getItemName()
         {
              return name;
         }
    
         public void setItemNumber(double number)
         {
              this.number = number;
         }
    
         public double getItemNumber()
         {
              return number;
         }
    
         public void setStockQuantity(long quantity)
         {
              stockQuantity = quantity;
         }
    
         public long getStockQuantity()
         {
              return stockQuantity;
         }
    
         public void setItemPrice(double price)
         {
              this.price = price;
         }
    
         public double getItemPrice()
         {
              return price;
         }
    
         public double calculateInventoryValue()
         {
              return getItemPrice() * getStockQuantity();
         }
    
         public int compareTo (Object o)
         {
              Product p = (Product)o;
              return name.compareTo(p.getItemName());
         }
    
         public String toString()
         {
              return "\nName: "+getItemName() + "\nNumber: "+number+"\nPrice: $"+price+"\nQuantity: "+stockQuantity + "\nValue: $"+calculateInventoryValue();
         }
    
    }//end Product
    
    class DVD extends Product implements Comparable
    {
         private String gender;
         public DVD()
         {
              super(); //call the constructor in Product
              gender = ""; //add the additonal attribute
         }
    
         public DVD(String name, int number, long stockQuantity, double price, String gender)
         {
              super(name, number, stockQuantity, price); //call the constructor in Product
              this.gender = gender; //add the additonal attribute
         }
    
         public void setGender(String gender)
         {
              this.gender = gender;
         }
    
         public String getGender()
         {
              return gender;
         }
    
         public double calculateInventoryValue()
         {
              return getItemPrice() * getStockQuantity();
         }
    
         public double calculateRestockFee()
         {
              return getItemPrice() * .05;
         }
    
         public int compareTo (Object o)
         {
              Product p = (Product)o;
              return getItemName().compareTo(p.getItemName());
         }
    
         public String toString()
         {
              return "\nName:   "+getItemName() + "\nNumber:   "+getItemNumber()+"\nPrice:   $"+getItemPrice()+"\nQuantity:   "
                   +getStockQuantity() +"\nGender:  "+getGender()+"\nValue:   $"+calculateInventoryValue();
         }
    
    } // end DVD
    
    public class RunInv extends JFrame implements ActionListener
    {
         //utility class for displaying the picture
         private class MyPanel extends JPanel
         {
              ImageIcon image = new ImageIcon("http://www.copticstore.com/images/dvd.jpg");
              int width = image.getIconWidth();
              int height = image.getIconHeight();
              long angle = 0;
              public MyPanel()
              {
                   super();
              }
    
              public void paintComponent(Graphics g)
              {
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D)g;
                   g2d.rotate (Math.toRadians(angle), 200+width/2, 90+height/2);
                   g2d.drawImage(image.getImage(), 5, 5, this);
                   g2d.dispose();
              }
    
         }//end class MyPanel
    
         int currentIndex; //currently displayed Item
         Product[] supplies = new Product[4];
         JLabel name ;
         JLabel number;
         JLabel gender;
         JLabel quantity;
         JLabel price;
         JLabel fee;
         JLabel totalValue;
         JTextField nameField = new JTextField(20);
         JTextField numberField = new JTextField(20);
         JTextField genderField = new JTextField(20);
         JTextField quantityField = new JTextField(20);
         JTextField priceField = new JTextField(20);
         JTextField totalValueField = new JTextField(20);
         JPanel display;
         JPanel displayHolder;
         JPanel panel;
    
         public RunInv()
         {
              makeTheDataItems();
              setSize(700,300);
              setTitle( "Inventory Program" );
    
              //make the panels
              display = new JPanel();
              JPanel other = new JPanel();
              JPanel picture = new MyPanel();
              JPanel buttons = new JPanel();
              JPanel centerPanel = new JPanel();
              displayHolder = new JPanel();
              display.setLayout(new GridLayout(3, 3));
              other.setLayout(new GridLayout(2, 1));
    
              //make the labels
              name = new JLabel("DVD Title:   ");
              number = new JLabel("Item Number:   ");
              gender = new JLabel("Gender:   ");
              quantity = new JLabel("Quantity:   ");
              price = new JLabel("Price:  $   ");
              fee = new JLabel("Fee:  $   ");
              totalValue = new JLabel("Total Value:  $   ");
    
              //make the buttons
              JButton first = makeButton("First");
              JButton next = makeButton("Next");
              JButton previous = makeButton("Previous");
              JButton last = makeButton("Last");
              JButton exit = makeButton("Exit");
    
              // other buttons
              JButton add = makeButton( "Add" );
              JButton delete = makeButton( "Delete" );
              JButton modify = makeButton( "Modify" );
              JButton save = makeButton( "Save" );
              JButton search = makeButton( "Search" );
    
              //add the labels to the display panel
              display.add(name);
              display.add(number);
              display.add(gender);
              display.add(quantity);
              display.add(price);
              display.add(fee);
              display.add(totalValue);
    
              //add the buttons to the buttonPanel
              buttons.add(first);
              buttons.add(previous);
              buttons.add(next);
              buttons.add(last);
              buttons.add(exit);
    
              //add the picture panel and display to the centerPanel
              displayHolder.add(display);
              centerPanel.setLayout(new GridLayout(2, 1));
              centerPanel.add(picture);
              centerPanel.add(displayHolder);
              other.add(buttons);
              JPanel forAdd = new JPanel(); // add the other buttons to this panel
                   forAdd.add( search );
                   forAdd.add( add );
                   forAdd.add( modify );
                   forAdd.add( delete );
                   forAdd.add( save );
                   other.add( forAdd );
              
              //add the panels to the frame
              getContentPane().add(centerPanel, "Center");
              getContentPane().add(other, "South");
              this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              setVisible(true);
         
         }//end RunInv
    
         private void makeTheDataItems ()
         {
              supplies[0] = new DVD("Fantastic 4", 1, 10, 19.99, "SciFi");
              supplies[1] = new DVD("Harry Potter 4", 2, 15, 15.50, "Fantacy");
              supplies[2] = new DVD("Die Hard", 3, 5, 9.99, "Action");
              supplies[3] = new DVD("The Simpsons Movie", 4, 30, 21.80, "Cartoon");
         }
    
         //method for creating and dressing buttons
         private JButton makeButton(String label)
         {
              JButton button = new JButton(label);
              button.setActionCommand(label);
              button.addActionListener(this);
              return button;
         }
    
         // start the add item method
         private void addItem()
         {
              System.out.println("Running Add Item Method");
              panel = new JPanel();
              JPanel add = new JPanel();
              add.setLayout(new GridLayout(2, 1));
              add.setLayout(new GridLayout(4, 4));
              JButton addIt = makeButton("Add Item");
              JLabel name = new JLabel("DVD Title :");
              JLabel gender = new JLabel("Gender :");
              JLabel quantity = new JLabel("Quantity :");
              JLabel price = new JLabel("Price :");
              add.add(name); add.add(nameField);
              add.add(gender); add.add(genderField);
              add.add(quantity); add.add(quantityField);
              add.add(price); add.add(priceField);
              panel.add(add);
              JPanel forAddIt = new JPanel();
              forAddIt.add(addIt);
              panel.add(forAddIt);
              displayHolder.remove(display);
              displayHolder.add(panel);
              this.setVisible(true);
    
         }//end addItem
    
    // End Add Item Method
    
    private void addItemToArray()
    {
         Product p = new DVD(nameField.getText(), supplies.length -2,
              Long.parseLong(quantityField.getText()),
              Double.parseDouble(priceField.getText()), genderField.getText());
         // extend size of array by one first
         Product[] ps = new Product[supplies.length + 1];
         for(int i = 0; i < ps.length-1; i++)
         {
              ps[i] = supplies[i];
         }
              ps[supplies.length] = p;
              supplies = ps;
              displayHolder.remove(panel);
              displayHolder.add(display);
              displayLast();
              this.setVisible(false);
              this.setVisible(true);
    
         } // end method addItemToArray
    
    
    // main methods begins execution of java application
    public static void main( String args[])
    {
         RunInv object = new RunInv();
    
    } // end main method
    
    public void actionPerformed(ActionEvent event)
    {
         String command = event.getActionCommand(); //retrieves command set for the button
    
         if(command.equals("First"))
         {
              System.out.print("First Button Clicked\n");// lets me know its working 
              displayFirst();
         }
         else if(command.equals("Next"))
         {
              System.out.printf("Next Button Clicked %s\n", currentIndex);// lets me know its working
              displayNext();
         }
         else if(command.equals("Previous"))
         {
              System.out.print("Previous Button Clicked\n");// lets me know its working
              displayPrevious();
         }
         else if(command.equals("Last"))
         {
              System.out.print("Last Button Clicked\n");// lets me know its working
              displayLast();
         }
         else if(command.equals("Exit"))
         {
              this.dispose();
              System.out.print("Thanks for using my program\nGood Bye!");// Exit Message
              System.exit(0);
         }
         else if(command.equals("Add"))
         {
              System.out.print("Add Button Clicked\n");// lets me know its working
              addItem();
         }
         else if(command.equals("Add Item"))
         {
              System.out.print("Enter new DVD\n");// enter new item
              addItemToArray();
         }
         else if(command.equals("Delete"))
         {
              System.out.print("This item will be deleted!\n");// delete item
              displayLast();
         }
         else if(command.equals("Modify"))
         {
              System.out.print("This item will be modified!\n");// modify item
         }
         else if(command.equals("Save"))
         {
              System.out.print("Save Button Clicked\n");// lets me know its working
              saveToFile();
         }
         else if(command.equals("Search"))
         {
              System.out.print("Searching for DVD!\n");// search for item
         }
    
    } // end action method
    
    private void saveToFile()
    {
         System.out.print("Array method Save To File\n");// lets me know its working
         FileWrite();
    
    } //end saveToFile
    
    private Formatter output;
    
         public void FileWrite()
         {
              System.out.print("Help\n");
      try{
    
         // Create file
         FileWriter fstream = new FileWriter("C:\\data\\inventory.dat");
         BufferedWriter out = new BufferedWriter(fstream);
         for (int i = 0; i < supplies.length; i++) {
         System.out.printf("%s\n", (DVD)supplies[i]);
         out.write(String.format("%s",(DVD)supplies[i]));
    
         }//end for
    
         //Close the output stream
         out.close();
         }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
         }
    
         }//end saveToFile
    
         //utility method to reduce lines of code
         private void displayItemAt(int index)
         {
              DVD product = (DVD)supplies[index];
              name.setText("DVD Title:   "+ product.getItemName());
              number.setText(String.format("Product Number:   %.0f%n",
              product.getItemNumber()));
              gender.setText("Gender:   "+ product.getGender());
              quantity.setText("Quantity In Stock:   "+ product.getStockQuantity());
              price.setText(String.format("Item Price:   $%.2f%n ", product.getItemPrice()));
              totalValue.setText(String.format("Total Value:   $%.2f%n ",
              product.calculateInventoryValue()));
              fee.setText(String.format("Fee :   $%.2f%n", product.calculateRestockFee()));
              this.setVisible(true);
         }
    
         public void displayFirst()
         {
              displayItemAt(0);
              currentIndex = 0;
         }
    
         public void displayNext()
         {
              if(currentIndex == supplies.length-1)
         {
              displayFirst();
              currentIndex = 0;
         }
         else
         {
              displayItemAt(currentIndex + 1);
              currentIndex++;
         }
         }
    
         public void displayPrevious()
         {
              if(currentIndex == 0)
         {
              displayLast();
              currentIndex = supplies.length-1;
         }
         else
         {
               displayItemAt(currentIndex - 1);
               currentIndex--;
         }
         }
    
         public void displayLast()
         {
              displayItemAt(supplies.length-1);
              currentIndex = supplies.length-1;
         }
        
         public void displayAdd()
         {
              displayItemAt(currentIndex++);
              if(currentIndex >= supplies.length)
              currentIndex = 0;
              displayAdd(); 
         }
    
         public void displayDelete()
         {
              currentIndex = supplies.length-1;
         } 
    
         public void displayModify()
         {
              currentIndex = 0;
         }         
    
    } //end class RunInv

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,270
    Rep Power
    25

    Default

    What does your program do when the buttons are pressed?
    having trouble getting the "Delete", "Modify", "Save", and "Search" buttons to function.
    What are the functions they are supposed to do?

    A suggestion: add a trailing else{} to the if {} else if{} chain in the actionPerformed() method as a default if none of the above tests were true to show what the uncaught value was.

  3. #3
    ljk8950 is offline Member
    Join Date
    Jul 2008
    Posts
    43
    Rep Power
    0

    Default

    Norm,

    I am sorry I was not more specific. The "Delete" button should allow the user to delete any item selected in the inventory program. The "Modify" button should allow the user to select an item and change the name, quantity, or price of that item. The "Save" button should allow the user to the save the document to the C:\data\inventory.dat file. Finally, the "Search" button should allow the user to type in the name of the DVD that the user would like to find. Thanks to anyone that can help me figure out how to get these buttons to function properly.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,270
    Rep Power
    25

    Default

    For each of the functions, you need to think thru the steps necessary to impliment them. You currently have the actionListener called when the button is pressed, so you have the place to put the code to do the task for each button press.
    You've gotten the Add function to work, now pick one of the functions and work on it. The rest of them will be more of the same: working on an array to do some function.
    For the Save function, you need to design the format of the output file. Then iterate thru the array and output a record for each element. The DVD class could have a method to build a record to be saved and to be symmetric, it should have a constructor to create a DVD object when a record is read in from a saved file.

    Suggestion (as I mentione before) write a small test program to do a function. Forget about the GUI do it in the main() method and maybe with one other static method. Create an array as in your current program and add elements to it and then say for Delete write a method to remove one element. Assume that the user has entered something and just hardcode it, forget about the GUI part for now. Later you can write the GUI to get the String you'll need from a user.
    Last edited by Norm; 08-15-2008 at 02:59 AM.

  5. #5
    ljk8950 is offline Member
    Join Date
    Jul 2008
    Posts
    43
    Rep Power
    0

    Default

    Norm,

    You provided me with good sound advice. I am going to work on it as you instructed. Wish me luck!

  6. #6
    ljk8950 is offline Member
    Join Date
    Jul 2008
    Posts
    43
    Rep Power
    0

    Default Reply to Norm

    Norm,

    I have been working on one Button at a time with no success. The button I am working on is the "Delete" button. I have tried every combination of codes I can think of. I thought delete is the opposite of add. It ccompiles but I get the following error. Please take a look at what I wrote for the delete function and let me know what I am doing wrong. Thank you!

    Error:

    Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For inpu
    t string: ""
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at RunInv.deleteItem(RunInv.java:331)
    at RunInv.actionPerformed(RunInv.java:401)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Sour
    ce)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)


    Java Code:
    private void deleteItem()
    {
         Product p = new DVD(nameField.getText(), supplies.length -2,
              Long.parseLong(quantityField.getText()),
              Double.parseDouble(priceField.getText()), genderField.getText());
         // remove size of array by one 
         Product[] ps = new Product[supplies.length - 1];
         for(int i = 0; i < ps.length-1; i++)
         {
              ps[i] = supplies[i];
         }
              ps[supplies.length] = p;
              supplies = ps;
              displayHolder.remove(panel);
              displayHolder.remove(display);
              displayLast();
              this.setVisible(false);
              this.setVisible(true);
    
    } // end method deleteItem

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,270
    Rep Power
    25

    Default

    at java.lang.Long.parseLong(Unknown Source)
    at RunInv.deleteItem(RunInv.java:331)
    at RunInv.actionPerformed(RunInv.java:401)
    What value does quantityField.getText() return? It looks like its a blank according to the error message. Put a valid long value in that field will keep it from being an exception.

    I guess you decided NOT to write a simple program to get the logic worked out for deleting an element from an array.

    Go back to your design work. How do you decide what element to delete? You are told by user by a button push. The currently viewed element is the one to be deleted. Call the delete method and give it the current item index. On return you need to refresh the display to show an element that is not deleted.

    Do you have a design for the delete method? If so, is one of the steps in your design to create a new Product? That looks like the first thing you do in the code above???

    Stop coding until you have a design.
    Last edited by Norm; 08-15-2008 at 04:47 PM.

Similar Threads

  1. GUI buttons question...
    By glenrowan in forum New To Java
    Replies: 3
    Last Post: 01-18-2011, 05:23 PM
  2. How to use SWT Buttons
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-11-2008, 04:44 PM
  3. Replies: 0
    Last Post: 06-23-2008, 11:16 PM
  4. Change Password Functionality
    By Priyadharshini.s in forum Advanced Java
    Replies: 5
    Last Post: 04-02-2008, 12:56 PM
  5. class wordprocessor with spellchecking functionality
    By manuniyi in forum AWT / Swing
    Replies: 1
    Last Post: 12-25-2007, 05:32 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •