Solved

Method in class not 'listening' to GUI class

Posted on 2011-03-02
9
269 Views
Last Modified: 2012-06-27
Please see the attached code, two classes, bookgui and bookshelf - i'm trying to get costofbookshelf to return the cost of bookshelf from the bookshelf class when the relevant button is pressed from the bookgui class but it's not doing anything, all compiles ok and to my inexperienced eye it all looks good but evidently not, any suggestions would be much appreciated.  thanks, theo
public class BookGUI extends JFrame implements ActionListener

{

	//String addBook="";
	// public ArrayList<Book> books;
	
	Book books = new Book ("", "", 0, "", 0);
	Book book = new Book("", "", 0, "", 0);
	String title  = "";
	String author  = "";
	int year = 0;
	String publisher  = "";
	double cost = 0;
	double total = 0;
		
	public BookShelf bookShelf = new BookShelf();
    public static final int WIDTH = 300;
    public static final int HEIGHT = 200;

    //Creates & displays a window of the class FlowLayoutDemo
    public static void main(String[] args)
    {
        BookGUI gui = new BookGUI( );
        gui.setVisible(true);
    }
    
   // public String getTitle()
   // {
    //    return title;
    //}
    
    public void setTitle(String title) //this is relevant
    {
        this.title = title;
    }
    
    public void setAuthor(String author) //this is relevant
    {
        this.author = author;
    }
    
    public void setYear(int year) //this is relevant
    {
        this.year = year;
    }
    public void setPublisher(String publisher) //this is relevant
    {
        this.publisher = publisher;
    }
    
    public void setCost(double cost) //this is relevant
    {
        this.cost = cost;
    }
    
    public BookGUI( )
    {
       
    	setSize(WIDTH, HEIGHT);
        addWindowListener(new WindowDestroyer( ));
        setTitle("GUI Assignment");
        Container content = getContentPane( );

        content.setLayout(new FlowLayout());
             
        JButton button1 = new JButton("Title");
        content.add(button1);
        button1.addActionListener(this);
        //contentPane.add(button1);
        
        JButton button2 = new JButton("Cost of Bookshelf");
        content.add(button2);
        button2.addActionListener(this);
        
        JButton button3 = new JButton("Size of BookShelf");
        content.add(button3);
        button3.addActionListener(this);
        
        JButton button4 = new JButton("Add Book");
        content.add(button4);
        button4.addActionListener(this);     
              
    }
         
    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Add Book"))
       //book = JOptionPane.showInputDialog("Add Book");
        {     //set up the book object with all the data passed in
        title = JOptionPane.showInputDialog("Title");
        author = JOptionPane.showInputDialog("Author");
        publisher = JOptionPane.showInputDialog("Publisher");
        //cost = JOptionPane.showInputDialog("Cost");
        //cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
        try { 
        	cost = Double.parseDouble(JOptionPane.showInputDialog("Cost")); 
        	} 
        	catch (NumberFormatException ex){ 
        	cost = 0.0; 
        	} 
        book.setTitle(title);
        book.setAuthor(author);
        book.setPublisher(publisher);
       	bookShelf.addBook(book);
        	
        String message =  "The title of the book is :" + title + 
		"the Author of the Book is : " + author + " and it's published by " + publisher + "and it costs" + cost + "euro";
        JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
        }
        else if (e.getActionCommand().equals("Size of BookShelf")) {
            int sizeOfBookShelf = bookShelf.sizeOfBookshelf();
            String message = "The book shelf has " + sizeOfBookShelf + " book(s)";
            JOptionPane.showMessageDialog(this, message);
        }
        else if (e.getActionCommand().equals("Cost of BookShelf")) 
        {
        	double costOfBookshelf = bookShelf.costOfBookshelf();
        	String message = "The book shelf value is " + total + costOfBookshelf + "Euro";
        	JOptionPane.showMessageDialog(this, message);
        }
   
    }
    }

Open in new window

import java.util.ArrayList;

/**
  * This class holds an ArrayList of Book.  There are methods for adding Book objects to the ArrayList,
  * calculating the total cost of all books in the ArrayList, determining how many Book objects are
  * in the ArrayList and determining the highest price paid for any one Book.
  *
  * @
  * @version 1.0
  */

public class BookShelf
{
    //create an ArrayList of Book.
    public ArrayList<Book> books;
    
    public BookShelf()
    {    
       books = new ArrayList<Book>();
    }

    /**
     * This method adds a Book object to the ArrayList
     * 
     * @param theBook The book object that will be added to the ArrayList
     * 
     */
    public void addBook(Book theBook)
    {
        books.add(theBook);
    }
    
    /**
     * This method returns the size of the ArrayList, that is, the number of books
     * that have been added to the ArrayList
     * 
     * @return The size of the ArrayList 
     */
    public int sizeOfBookshelf()
    {
        return books.size();
    }
    
    /**
     * This method calculates the cost of the book shelf, that is, it totals the 
     * cost of all the books in the ArrayList and returns it.
     * 
     * @return The cost of the book shelf
     */
    public double costOfBookshelf(){
        
        double total = 0;
        
        for(Book book : books) {
            total = total + book.getCost();
        }
        return total;
    }
        
    
    //create a method called highestPricePAid that will return the cost of the most expensive book in the ArrayList

    /**
     * This method finds the price of the most expensive book in the ArrayList and returns it.
     * 
     * @return The cost of the most expensive book on the book shelf
     */
    public double highestPricePaid(){
        
       double highestPrice = 0;
       
       for(Book book : books) {
                     
            if((highestPrice == 0) || (highestPrice < book.getCost())) { 
                highestPrice = book.getCost(); }
       }
       
       return highestPrice;
    }
         
}

Open in new window

0
Comment
Question by:t38
  • 4
  • 3
  • 2
9 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 350 total points
ID: 35016772
>               cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));

you never set the cost of the book

use:

cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
book.setCost(cost);
0
 

Author Comment

by:t38
ID: 35016829
hi, thanks for the prompt response, i added the book.setCost(cost); as suggested but i'm still not getting a value returned?


try {
              cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
              book.setCost(cost);
              }
              catch (NumberFormatException ex){
              cost = 0.0;
              }
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 150 total points
ID: 35016832
Change

>>else if (e.getActionCommand().equals("Cost of BookShelf")) {

to
else if (e.getActionCommand().equalsIgnoreCase("Cost of BookShelf")) {

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:t38
ID: 35016910
i'll try that thanks CEJH, what's 'IgnoreCase' doing?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35016917
(Or probably better the below - since it then matches the command)
} else if (e.getActionCommand().equals("Cost of Bookshelf")) {

Open in new window

0
 
LVL 92

Accepted Solution

by:
objects earned 350 total points
ID: 35016919
>         JButton button2 = new JButton("Cost of Bookshelf");

you made shelf lowercase
make it


        JButton button2 = new JButton("Cost of BookShelf");

>         else if (e.getActionCommand().equals("Cost of BookShelf"))

though safer to change this line to not be case sensitive


        else if (e.getActionCommand().equalsIgnoreCase("Cost of BookShelf"))
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35016962
I would advise against matching on action commands - it's error prone (as you've just demonstrated) and less efficient than the below
Object source = e.getSource();
....
if (source == bnShelfCost) { // make your button names more self-documenting
   // Calculate cost
}

Open in new window

0
 

Author Closing Comment

by:t38
ID: 35016997
Thanks for your contributions, they all helped in getting to the answer.  theo
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35017009
t38, can you explain why you accepted the answer that simply repeats what i'd already stated?
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Way to decrease size of apk file 9 104
going to wrong jsp page 2 46
Netbeans and org.apache.commons.lang3 issue 3 22
Java array 21 75
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question