Solved

Method in class not 'listening' to GUI class

Posted on 2011-03-02
9
266 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
 

Author Comment

by:t38
ID: 35016910
i'll try that thanks CEJH, what's 'IgnoreCase' doing?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
advertisement module in core php 4 145
Spring Framework HTTPSession management 1 23
javap bin 2 27
web services creation SOAP vs REST 5 19
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

910 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now