Solved

Method in class not 'listening' to GUI class

Posted on 2011-03-02
9
265 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
Comment Utility
>               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
Comment Utility
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
Comment Utility
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
Comment Utility
i'll try that thanks CEJH, what's 'IgnoreCase' doing?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(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
Comment Utility
>         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
Comment Utility
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
Comment Utility
Thanks for your contributions, they all helped in getting to the answer.  theo
0
 
LVL 86

Expert Comment

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

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 40
word0 challenge 3 56
JAVA part two 5 39
micro services vs rest web services 16 45
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…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

744 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

9 Experts available now in Live!

Get 1:1 Help Now