Solved

Method in class not 'listening' to GUI class

Posted on 2011-03-02
9
271 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
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 …
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…
Suggested Courses

630 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