• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2015
  • Last Modified:

Cannot make a static reference to the non-static method

Please see attached code, I've been poring over it for ages but can't figure out how to get around the error "  and get it to populate the database.  any suggestions much appreciated.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
      Cannot make a static reference to the non-static method insertRow(int, String, String, String, int, double) from the type BookGUI

      at database.BookGUI.main(BookGUI.java:47)

package database;

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener; 
import java.sql.*;

	/**
	 * This class operates as the graphical user interface that interacts with the 
	 * Book and BookShelf classes to add Books to the array and return 
	 * a graphical representation of information from the BookShelf methods.  
	 * 
	 * 
	 */

public class BookGUI extends JFrame implements ActionListener
{
	static Connection link;
	static Statement statement;
	static ResultSet results;
	
	// Declare the instance variables for the class
	private String title  = "";
	private String author  = "";
	private String publisher  = "";
	private int year = 0;
	private double cost = 0;
    private boolean goodInput = false;
    
	
	// Define the exact dimensions of the graphical interface
    private static final int WIDTH = 600;
   	private static final int HEIGHT = 90;
   	private BookShelf bookShelf;
	
    

    public static void main(String[] args)
    {
    	//public Insert()
    	{
    		try
    		{
    			
    			insertRow(25, "Test Five", "Stephen King", "Publish", 2000, 20.0);
    			
    		}
    		catch (SQLException e)
    		{
    			System.out.println("Message: " + e.getMessage());
    			System.out.println("SQL State: " + e.getSQLState());
    			System.out.println("SQL Error Code: " + e.getErrorCode());
    			e.printStackTrace();
    			System.exit(1);
    		}
    	
    	}
   	
    	
    	try{
			//Step 1
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			//Step 2
			link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
			statement = link.createStatement();
			
			System.out.println("linl: " + link);


			
			 System.out.println("statn: " + statement);

		}
		catch(ClassNotFoundException e){
			System.out.println("Unable to load driver");
			System.exit(1);
		}
		catch(SQLException e){
			System.out.println("Cannot connect to the database");
			System.exit(1);
		}
	
		new BookGUI();
		
	//End main
       
//COMPILING AND RUNNING AS FAR AS HERE
		
		
		
    	
    	BookGUI gui = new BookGUI( );
       gui.setVisible(true);
    }
   
    
    public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost) throws SQLException
	  {
		  String insert = "INSERT INTO BookShelf"
            + " VALUES (" + ID   + ", " 
                          + "'" + Title + "', "
                          + "'" + Author   + "','"
                          + Publisher + "', " + Year +"," +  Cost   + ")";

System.out.println(insert);

System.out.println("statn: " + statement);

 
	       
	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       { 
	    	  System.out.println("Failed to insert the following data: " 
	    			         + ID   + "," 
                           + Title + ","
                           + Author   + ","
                           + Publisher   + ","
                           + Year   + ","
                           + Cost);
	  }
	
	link.close();
	
	
	

	  }
		
     
    /**
     * Create the GUI frame with buttons and listeners
     */
    public BookGUI( )
    {
        // Create a new instance of BookShelf	
    	//bookShelf = new BookShelf();
    	
        JFrame frame = this; 
     	
        // Create the main frame's menu bar.
        JMenuBar menubar = new JMenuBar();
    	frame.setJMenuBar(menubar);
    	frame.pack();
    	frame.setVisible(true);
    	
    	//  Create the File menu
    	JMenu fileMenu = new JMenu("File");
    	menubar.add(fileMenu);
    	
    	// Create a Quit option on the File menu
    	JMenuItem quitItem = new JMenuItem("Quit");
    	fileMenu.add(quitItem);
    	quitItem.addActionListener(this); 
    	
    	// create the About menu
    	JMenu aboutMenu = new JMenu ("About");
    	menubar.add(aboutMenu);
    	
    	JMenuItem infoItem = new JMenuItem("Info");
    	aboutMenu.add(infoItem);
    	infoItem.addActionListener(this);
    	
    	//Set the Size of the frame    	
    	setSize(WIDTH, HEIGHT);
      
    	// Create a new instance of the WindowDestroyer class
        addWindowListener(new WindowDestroyer( ));
        setTitle("GUI Assignment");
        Container content = getContentPane( );

        
        // Arrange the buttons on the GUI in a Flow Layout
        content.setLayout(new FlowLayout());
             
        // Set up the required buttons on the GUI and the corresponding listener for that action.
        JButton button1 = new JButton("Add Book");
        content.add(button1);
        button1.addActionListener(this); 
        
        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("Highest Price Paid");
        content.add(button4);
        button4.addActionListener(this);
        
        }
    
   /**
    * These methods perform the corresponding action when the buttons on the GUI are clicked.
    * Exception handling in these methods ensure the correct values are entered.  If not, the 
    * user is prompted to re-enter the data correctly.
    * 
    * @param e holds the event that was fired.
    */
    public void actionPerformed(ActionEvent e)
    {
    	if (e.getActionCommand().equals("Add Book"))
        {    
    	   Book book = new Book("", "", 0, "", 0);
    	   title = JOptionPane.showInputDialog("Title");
           author = JOptionPane.showInputDialog("Author");
           publisher = JOptionPane.showInputDialog("Publisher");
        
           do{
              try 
              { 
        	     cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
        	     book.setCost(cost);
        	     goodInput = true;
        	  } 
              catch (Exception cE){          
                 JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for cost");
        	  } 
           }while (!goodInput);

  	       goodInput = false;
           do{
               try 
               { 
         	     year = Integer.parseInt(JOptionPane.showInputDialog("Year"));
         	     book.setYear(year);
         	     goodInput = true;
         	  } 
               catch (Exception yE){          
                  JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for year");
         	  } 
            }while (!goodInput);
           
            //Add an instance of book to the ArrayList
            bookShelf.addBook(book);
        	
            String message =  "The Title of the book is " + title 
                           +  " the Author of the Book is "  + author 
                           + " it's published by " + publisher 
                           + " in " + year
                           + " and it costs " + cost + " euro ";
            JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
        }
        else if (e.getActionCommand().equals("Size of BookShelf")) 
        {
           String message = "The book shelf has " + bookShelf.sizeOfBookshelf() + " book(s)";
           JOptionPane.showMessageDialog(this, message);
        }
        else if (e.getActionCommand().equals("Cost of BookShelf")) 
        {
           String message = "The book shelf value is " + bookShelf.costOfBookShelf() + "Euro";
           JOptionPane.showMessageDialog(this, message);
        }
    	else if (e.getActionCommand().equals("Info"))
        {
        	JOptionPane.showMessageDialog(this, "Tony O'Keeffe - GUI Assignment One");
        }
        else if (e.getActionCommand().equals("Highest Price Paid"))
        {          
            String message = "The highest price paid for a book is: " + bookShelf.highestPricePaid() + "Euro";
            JOptionPane.showMessageDialog(this, message);
        } 
        else
        {
            System.exit( 0 );
        }
    	
     } // end actionPerformed

} //end BookGUI class

Open in new window

0
t38
Asked:
t38
  • 20
  • 12
  • 4
2 Solutions
 
for_yanCommented:
You need to instantiate

BookGui bg = new BokGui();
and then
bg.insertRow(...)
0
 
for_yanCommented:


main() is a static method from this method you cannot call non-static methods

so you either have to make insertRow() static
or you need to have an instance of your calss and call insertRow and an instance method
0
 
t38Author Commented:
thanks, could you possibly explain a little more explicitly please?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
for_yanCommented:
insertRow cannot be a static method, becuase it uses intsnace variables like statment,
so you have to instantiate your class and execute insetRow() as a method on that instance, as I showed
0
 
t38Author Commented:
thanks, i asked for clarification before i saw you're second entry, i'm just implementing same now and will report back shortly
0
 
for_yanCommented:

When you declare a method static it means that this
is a method not depening on particluar instance of the class.

Say in the class circle you may have static method area()

class Circle {

public static double area(double r){
return Math.pi*r*r;
}

}

as you see you provvide radius and retirn area - that
is and ideal of area of the circle not connected to any specific instance.
You can call thios method like that, attaching method to the name of the class not to particular instance:

Circle.area(5.0);

You can have different kind of method:

class Circle {
double r;

public Circle(double r){
this.r = r;
}

double area(){
return Math.pi*r*r;

}


}

To call such method (instance method) you need
first to create instance of your circle via constructor.
You'll call it this way somehwre in this class code ior in osme other class of the same app:

Cicrle c = new Circle(5.0);
double ar = c.area();


This is instance method depndding on particular instance.

Static methods inside themselved cannot refere to instance variables or instance
methods - if you think a bit you'll understadn - they need to be indleendent of
any instance

As main() has ti be static - it cannot refer to any instance
methods. Therefore you cannot run instance method
within main, unless it is attached to instance of the class, as I showed.

In general it is bad practice to put lots of code in main().
In main you instantoate instance of the
class, and placve most of the stuff into contruyctor
and instance methods (as I did in my code - which I posted in the
previous question yesterday).
 

0
 
for_yanCommented:
If you think of it a little bit more
your insertRow() uses statement, which is instance
varaible of your class.
If you just try to use it as you inteneded in main()
you haven't yet initialized any instances, so your statement
is not defined - so it cannot execute in main() by itslef.

When I furst created instance with the constructor I in fact
somehow initiated instance varaible, say statement in this case.
Therefore, when I say
bg.insertRow()
it will already know that it should take statement
variable as it is contained in the bg instance.
So this disticntion between static and instance methods is actually very logical, though seems
a little bit not so easy to understand in the beginning
0
 
objectsCommented:
try something like this:

your insertRow() method would probably be better off in another class
import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.sql.*;

/**
 * This class operates as the graphical user interface that interacts with the
 * Book and BookShelf classes to add Books to the array and return a graphical
 * representation of information from the BookShelf methods.
 * 
 * 
 */

public class BookGUI extends JFrame implements ActionListener {
	// Declare the instance variables for the class
	private String title = "";
	private String author = "";
	private String publisher = "";
	private int year = 0;
	private double cost = 0;
	private boolean goodInput = false;

	// Define the exact dimensions of the graphical interface
	private static final int WIDTH = 600;
	private static final int HEIGHT = 90;
	private BookShelf bookShelf;

	public static void main(String[] args) {
		Connection link;
		Statement statement;

		try {
			// Step 1
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			// Step 2
			link = DriverManager.getConnection("jdbc:odbc:BookShelf", "", "");
			statement = link.createStatement();

			System.out.println("linl: " + link);

			System.out.println("statn: " + statement);

			insertRow(link, statement, 25, "Test Five", "Stephen King",
					"Publish", 2000, 20.0);

		} catch (ClassNotFoundException e) {
			System.out.println("Unable to load driver");
			System.exit(1);
		} catch (SQLException e) {
			System.out.println("Cannot connect to the database");
			System.exit(1);
		}

		// End main

		// COMPILING AND RUNNING AS FAR AS HERE

		BookGUI gui = new BookGUI();
		gui.setVisible(true);
	}

	private static void insertRow(Connection link, Statement statement, int ID,
			String Title, String Author, String Publisher, int Year, double Cost)
			throws SQLException {
		String insert = "INSERT INTO BookShelf" + " VALUES (" + ID + ", " + "'"
				+ Title + "', " + "'" + Author + "','" + Publisher + "', "
				+ Year + "," + Cost + ")";

		System.out.println(insert);

		System.out.println("statn: " + statement);

		int result = statement.executeUpdate(insert);
		if (result == 0) {
			System.out.println("Failed to insert the following data: " + ID
					+ "," + Title + "," + Author + "," + Publisher + "," + Year
					+ "," + Cost);
		}

		link.close();

	}

	/**
	 * Create the GUI frame with buttons and listeners
	 */
	public BookGUI() {
		// Create a new instance of BookShelf
		// bookShelf = new BookShelf();

		JFrame frame = this;

		// Create the main frame's menu bar.
		JMenuBar menubar = new JMenuBar();
		frame.setJMenuBar(menubar);
		frame.pack();
		frame.setVisible(true);

		// Create the File menu
		JMenu fileMenu = new JMenu("File");
		menubar.add(fileMenu);

		// Create a Quit option on the File menu
		JMenuItem quitItem = new JMenuItem("Quit");
		fileMenu.add(quitItem);
		quitItem.addActionListener(this);

		// create the About menu
		JMenu aboutMenu = new JMenu("About");
		menubar.add(aboutMenu);

		JMenuItem infoItem = new JMenuItem("Info");
		aboutMenu.add(infoItem);
		infoItem.addActionListener(this);

		// Set the Size of the frame
		setSize(WIDTH, HEIGHT);

		// Create a new instance of the WindowDestroyer class
		addWindowListener(new WindowDestroyer());
		setTitle("GUI Assignment");
		Container content = getContentPane();

		// Arrange the buttons on the GUI in a Flow Layout
		content.setLayout(new FlowLayout());

		// Set up the required buttons on the GUI and the corresponding listener
		// for that action.
		JButton button1 = new JButton("Add Book");
		content.add(button1);
		button1.addActionListener(this);

		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("Highest Price Paid");
		content.add(button4);
		button4.addActionListener(this);

	}

	/**
	 * These methods perform the corresponding action when the buttons on the
	 * GUI are clicked. Exception handling in these methods ensure the correct
	 * values are entered. If not, the user is prompted to re-enter the data
	 * correctly.
	 * 
	 * @param e
	 *            holds the event that was fired.
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("Add Book")) {
			Book book = new Book("", "", 0, "", 0);
			title = JOptionPane.showInputDialog("Title");
			author = JOptionPane.showInputDialog("Author");
			publisher = JOptionPane.showInputDialog("Publisher");

			do {
				try {
					cost = Double.parseDouble(JOptionPane
							.showInputDialog("Cost"));
					book.setCost(cost);
					goodInput = true;
				} catch (Exception cE) {
					JOptionPane
							.showMessageDialog(this,
									"Numerical entry required. Please re-enter a value for cost");
				}
			} while (!goodInput);

			goodInput = false;
			do {
				try {
					year = Integer
							.parseInt(JOptionPane.showInputDialog("Year"));
					book.setYear(year);
					goodInput = true;
				} catch (Exception yE) {
					JOptionPane
							.showMessageDialog(this,
									"Numerical entry required. Please re-enter a value for year");
				}
			} while (!goodInput);

			// Add an instance of book to the ArrayList
			bookShelf.addBook(book);

			String message = "The Title of the book is " + title
					+ " the Author of the Book is " + author
					+ " it's published by " + publisher + " in " + year
					+ " and it costs " + cost + " euro ";
			JOptionPane.showMessageDialog(null, message, "Book Details",
					JOptionPane.PLAIN_MESSAGE);
		} else if (e.getActionCommand().equals("Size of BookShelf")) {
			String message = "The book shelf has "
					+ bookShelf.sizeOfBookshelf() + " book(s)";
			JOptionPane.showMessageDialog(this, message);
		} else if (e.getActionCommand().equals("Cost of BookShelf")) {
			String message = "The book shelf value is "
					+ bookShelf.costOfBookShelf() + "Euro";
			JOptionPane.showMessageDialog(this, message);
		} else if (e.getActionCommand().equals("Info")) {
			JOptionPane.showMessageDialog(this,
					"Tony O'Keeffe - GUI Assignment One");
		} else if (e.getActionCommand().equals("Highest Price Paid")) {
			String message = "The highest price paid for a book is: "
					+ bookShelf.highestPricePaid() + "Euro";
			JOptionPane.showMessageDialog(this, message);
		} else {
			System.exit(0);
		}

	} // end actionPerformed

} // end BookGUI class

Open in new window

0
 
for_yanCommented:
You can also say, that instance methods chracterize properties or behaviours
of particular instance of the object of the class, wheras static methods are associated
with the notion of the ovbject represented by class - in once case it gives
you the area of this particular circle, in another case it just provides method
of how to calculate any area of any circle - somthing like that.
Hope it gives you some clue
0
 
t38Author Commented:
Thanks for all the input, I will not be in position to implement recommend until later but will report back
0
 
t38Author Commented:
i''ve mplemented some changes but i'm still missing something fundamental, could you take a look at my changed code below and tell me if i'm on the right track please?
package database;

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener; 
import java.sql.*;

	/**
	 * This class operates as the graphical user interface that interacts with the 
	 * Book and BookShelf classes to add Books to the array and return 
	 * a graphical representation of information from the BookShelf methods.  
	 * 
	 * 
	 */

public class BookGUI extends JFrame implements ActionListener
{
	static Connection link;
	static Statement statement;
	static ResultSet results;
	
	// Declare the instance variables for the class
	private String title  = "";
	private String author  = "";
	private String publisher  = "";
	private int year = 0;
	private double cost = 0;
    private boolean goodInput = false;
    
	
	// Define the exact dimensions of the graphical interface
    private static final int WIDTH = 600;
   	private static final int HEIGHT = 90;
   	private BookShelf bookShelf;
	
    

    public static void main(String[] args)
    {
    	       
	   BookGUI gui = new BookGUI( );
       gui.setVisible(true);
    }
    
    public void Insert()
	{
    	try{
    		//Step 1
    		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		//Step 2
    		link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
    		statement = link.createStatement();
    		
    		System.out.println("linl: " + link);


    		
    		 System.out.println("statn: " + statement);

    	}
    	catch(ClassNotFoundException e){
    		System.out.println("Unable to load driver");
    		System.exit(1);
    	}
    	catch(SQLException e){
    		System.out.println("Cannot connect to the database");
    		System.exit(1);
    	}
    	
    	try
		{
			
			insertRow(26, "Test Five", "Stephen King", "Publish", 2000, 20.0);
			
		}
		catch (SQLException e)
		{
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQL State: " + e.getSQLState());
			System.out.println("SQL Error Code: " + e.getErrorCode());
			e.printStackTrace();
			System.exit(1);
		}
	
	

	new Insert();
	}
//End main
    
    
    
    public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost) throws SQLException
	  {
		  String insert = "INSERT INTO BookShelf"
            + " VALUES (" + ID   + ", " 
                          + "'" + Title + "', "
                          + "'" + Author   + "','"
                          + Publisher + "', " + Year +"," +  Cost   + ")";

System.out.println(insert);

System.out.println("statn: " + statement);

 
	       
	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       { 
	    	  System.out.println("Failed to insert the following data: " 
	    			         + ID   + "," 
                           + Title + ","
                           + Author   + ","
                           + Publisher   + ","
                           + Year   + ","
                           + Cost);
	  }
	
	link.close();
	
	  }
		
     
    /**
     * Create the GUI frame with buttons and listeners
     */
    public BookGUI( )
    {
        // Create a new instance of BookShelf	
    	bookShelf = new BookShelf();
    	
        JFrame frame = this; 
     	
        // Create the main frame's menu bar.
        JMenuBar menubar = new JMenuBar();
    	frame.setJMenuBar(menubar);
    	frame.pack();
    	frame.setVisible(true);
    	
    	//  Create the File menu
    	JMenu fileMenu = new JMenu("File");
    	menubar.add(fileMenu);
    	
    	// Create a Quit option on the File menu
    	JMenuItem quitItem = new JMenuItem("Quit");
    	fileMenu.add(quitItem);
    	quitItem.addActionListener(this); 
    	
    	// create the About menu
    	JMenu aboutMenu = new JMenu ("About");
    	menubar.add(aboutMenu);
    	
    	JMenuItem infoItem = new JMenuItem("Info");
    	aboutMenu.add(infoItem);
    	infoItem.addActionListener(this);
    	
    	//Set the Size of the frame    	
    	setSize(WIDTH, HEIGHT);
      
    	// Create a new instance of the WindowDestroyer class
        addWindowListener(new WindowDestroyer( ));
        setTitle("GUI Assignment");
        Container content = getContentPane( );

        
        // Arrange the buttons on the GUI in a Flow Layout
        content.setLayout(new FlowLayout());
             
        // Set up the required buttons on the GUI and the corresponding listener for that action.
        JButton button1 = new JButton("Add Book");
        content.add(button1);
        button1.addActionListener(this); 
        
        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("Highest Price Paid");
        content.add(button4);
        button4.addActionListener(this);
        
        }
    
   /**
    * These methods perform the corresponding action when the buttons on the GUI are clicked.
    * Exception handling in these methods ensure the correct values are entered.  If not, the 
    * user is prompted to re-enter the data correctly.
    * 
    * @param e holds the event that was fired.
    */
    public void actionPerformed(ActionEvent e)
    {
    	if (e.getActionCommand().equals("Add Book"))
        {    
    	   Book book = new Book("", "", 0, "", 0);
    	   title = JOptionPane.showInputDialog("Title");
           author = JOptionPane.showInputDialog("Author");
           publisher = JOptionPane.showInputDialog("Publisher");
        
           do{
              try 
              { 
        	     cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
        	     book.setCost(cost);
        	     goodInput = true;
        	  } 
              catch (Exception cE){          
                 JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for cost");
        	  } 
           }while (!goodInput);

  	       goodInput = false;
           do{
               try 
               { 
         	     year = Integer.parseInt(JOptionPane.showInputDialog("Year"));
         	     book.setYear(year);
         	     goodInput = true;
         	  } 
               catch (Exception yE){          
                  JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for year");
         	  } 
            }while (!goodInput);
           
            //Add an instance of book to the ArrayList
            bookShelf.addBook(book);
        	
            String message =  "The Title of the book is " + title 
                           +  " the Author of the Book is "  + author 
                           + " it's published by " + publisher 
                           + " in " + year
                           + " and it costs " + cost + " euro ";
            JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
        }
        else if (e.getActionCommand().equals("Size of BookShelf")) 
        {
           String message = "The book shelf has " + bookShelf.sizeOfBookshelf() + " book(s)";
           JOptionPane.showMessageDialog(this, message);
        }
        else if (e.getActionCommand().equals("Cost of BookShelf")) 
        {
           String message = "The book shelf value is " + bookShelf.costOfBookShelf() + "Euro";
           JOptionPane.showMessageDialog(this, message);
        }
    	else if (e.getActionCommand().equals("Info"))
        {
        	JOptionPane.showMessageDialog(this, "Tony O'Keeffe - GUI Assignment One");
        }
        else if (e.getActionCommand().equals("Highest Price Paid"))
        {          
            String message = "The highest price paid for a book is: " + bookShelf.highestPricePaid() + "Euro";
            JOptionPane.showMessageDialog(this, message);
        } 
        else
        {
            System.exit( 0 );
        }
    	
     } // end actionPerformed

} //end BookGUI class

Open in new window

0
 
for_yanCommented:
No, I don't think it is OK.
One thing is that if Insert() is a constructor (the name matches
the class name) then you can say

 new Insert()

If

public void Insert()

is a method
the way you call method is simply:

Insert();

More importantly, your call to Insert()
(actually new Insert()) happens inside
public void Insert() method
I guess this is not what you wanted


In teerms of calling non-stattic from static at this point
I don't see any errors.

Pleae, look at waht I wrote, if you want
post all your classes  I can try to check it all,
though if you fisrt look at the overall logic
and clean it, maybe it would be easier for me.



0
 
objectsCommented:
>  and tell me if i'm on the right track please?

you're getting there. the connection, statement and result set should only be local variables.
See the code I posted above for what I mean.
0
 
for_yanCommented:
At least connection, statement and result  should not be static.
But we already once already removed static from them - I rememeber - how
they again became static ?
0
 
objectsCommented:
>     public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost) throws SQLException

insertRow() can also be static.
Have a look at what I posted above and let me know if you have any questions
0
 
t38Author Commented:
thanks again for the comments (and your patience) i'm new to this stuff so a bit slow on the uptake to saythe least, i won't be able to apply your suggestions until later today and will report back then.
0
 
t38Author Commented:
please see attached code, i get errors unless i declare the statement and link variables twice, this is hardly right??  also i'm not sure where new Insert(); should be located?  any suggestions appreciated....
package database;

import java.sql.*;


public class Insert {
	
	Connection link;
	Statement statement;
	ResultSet results;

	
	public static void main(String[] args){
		
		Connection link;
		Statement statement;
		ResultSet results;

		
		
		try{
			//Step 1
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			//Step 2
			link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
			statement = link.createStatement();
			
			System.out.println("linl: " + link);

			
			
			 System.out.println("statn: " + statement);

		}
		catch(ClassNotFoundException e){
			System.out.println("Unable to load driver");
			System.exit(1);
		}
		catch(SQLException e){
			System.out.println("Cannot connect to the database");
			System.exit(1);
		}
	
		//new Insert();
		
	} //End main
	
	public Insert()
	
	{
		try
		{
			
			insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0);
			
		}
		catch (SQLException e)
		{
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQL State: " + e.getSQLState());
			System.out.println("SQL Error Code: " + e.getErrorCode());
			e.printStackTrace();
			System.exit(1);
		}
	
	}
		
	
	public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost) throws SQLException
	
	{
		  String insert = "INSERT INTO BookShelf"
              + " VALUES (" + ID   + ", " 
                            + "'" + Title + "', "
                            + "'" + Author   + "','"
                            + Publisher + "', " + Year +"," +  Cost   + ")";

  System.out.println(insert);
  
  System.out.println("statn: " + statement);

   
	       
	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       { 
	    	  System.out.println("Failed to insert the following data: " 
	    			         + ID   + "," 
                             + Title + ","
                             + Author   + ","
                             + Publisher   + ","
                             + Year   + ","
                             + Cost);
	  }
	
	link.close();
	
	new Insert();
	

	  }
}

Open in new window

0
 
for_yanCommented:
This is because instance variables cannot be referenced inside srtatic main) method.
When you declare them second tiime those are local variables -
and inside main() you in fact operate iwt local entities - they are diffferent from instance.

This is of course all not correct.

You shoul take some time and try to understand
difference between  instance fields - those are properties
of the instance of the class, static variables - those are properites
of the class itself - not of any particular instance but of the class as
a notion, and local variables - which live just within
the closest enclosed braces - within the method, or even only within the
loop.

In general you should never do a lot of stuff in this static method
main() .

In main() you usuailly instaiate instance of your class, and
the main work should be done either in the constructor of the class or in the
instance methods. Ten you'll be able to
to use instance variables - both in constrructor and in instnce methods
you can use instance variables.

In the static main() method you cannot use instance variables.
This is understandable - static methods are properties of
the whole class, they are not related to particular instance and therefore
cannot operate with the proprties/fields of  the instance


0
 
t38Author Commented:
yes of course, my mistake.  regarding new Insert() where should this be located?
0
 
for_yanCommented:
In general move all your actually doing studff code to constructrort
or to method and
in your main()
should basicelly be only

be  somethinglike that

Insert in = new Insert();
in.method();

or you can even call method
from constructor

then whole of uyour main would be


public static void main(String [] args){
new Insert();
}

Try to devise it all in sucvh way
0
 
for_yanCommented:


Then in constructor, in instance methods you can freely use your instance variables, you can
feel safe that they will be the same both in cosntructor and instance mthodds
and you'll not need (and should not) declare them again anywhere.

TTry to rewrite it this way.
Loo at may code which I sent you several days ago
which was organized like that - you may only want
to move actuall inster from that my code into separate metod
and say make a loop to call theis method - but all of
that should not happen in  main()

Try to do it this way and post it - and we'll look at it together
0
 
t38Author Commented:
like this?
package database;

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener; 
import java.sql.*;

	/**
	 * This class operates as the graphical user interface that interacts with the 
	 * Book and BookShelf classes to add Books to the array and return 
	 * a graphical representation of information from the BookShelf methods.  
	 * 
	 * 
	 */

public class BookGUI extends JFrame implements ActionListener
{
	public Connection link;
	public Statement statement;
	static ResultSet results;
	
	// Declare the instance variables for the class
	private String title  = "";
	private String author  = "";
	private String publisher  = "";
	private int year = 0;
	private double cost = 0;
    private boolean goodInput = false;
    
	
	// Define the exact dimensions of the graphical interface
    private static final int WIDTH = 600;
   	private static final int HEIGHT = 90;
   	private BookShelf bookShelf;
	
    

    public static void main(String[] args)
    {
    	       
	   BookGUI gui = new BookGUI( );
       gui.setVisible(true);
       Insert insert = new Insert();
    }
    
    public void Insert()
	{
    	try{
    		//Step 1
    		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		//Step 2
    		link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
    		statement = link.createStatement();
    		
    		System.out.println("linl: " + link);


    		
    		 System.out.println("statn: " + statement);

    	}
    	catch(ClassNotFoundException e){
    		System.out.println("Unable to load driver");
    		System.exit(1);
    	}
    	catch(SQLException e){
    		System.out.println("Cannot connect to the database");
    		System.exit(1);
    	}
    	
    	try
		{
			
			insertRow(26, "Test Five", "Stephen King", "Publish", 2000, 20.0);
			
		}
		catch (SQLException e)
		{
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQL State: " + e.getSQLState());
			System.out.println("SQL Error Code: " + e.getErrorCode());
			e.printStackTrace();
			System.exit(1);
		}
	
	

	
	}
//End main
    
    
    
    public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost) throws SQLException
	  {
		  String insert = "INSERT INTO BookShelf"
            + " VALUES (" + ID   + ", " 
                          + "'" + Title + "', "
                          + "'" + Author   + "','"
                          + Publisher + "', " + Year +"," +  Cost   + ")";

System.out.println(insert);

System.out.println("statn: " + statement);

 
	       
	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       { 
	    	  System.out.println("Failed to insert the following data: " 
	    			         + ID   + "," 
                           + Title + ","
                           + Author   + ","
                           + Publisher   + ","
                           + Year   + ","
                           + Cost);
	  }
	
	link.close();
	
	  }
		
     
    /**
     * Create the GUI frame with buttons and listeners
     */
    public BookGUI( )
    {
        // Create a new instance of BookShelf	
    	bookShelf = new BookShelf();
    	
        JFrame frame = this; 
     	
        // Create the main frame's menu bar.
        JMenuBar menubar = new JMenuBar();
    	frame.setJMenuBar(menubar);
    	frame.pack();
    	frame.setVisible(true);
    	
    	//  Create the File menu
    	JMenu fileMenu = new JMenu("File");
    	menubar.add(fileMenu);
    	
    	// Create a Quit option on the File menu
    	JMenuItem quitItem = new JMenuItem("Quit");
    	fileMenu.add(quitItem);
    	quitItem.addActionListener(this); 
    	
    	// create the About menu
    	JMenu aboutMenu = new JMenu ("About");
    	menubar.add(aboutMenu);
    	
    	JMenuItem infoItem = new JMenuItem("Info");
    	aboutMenu.add(infoItem);
    	infoItem.addActionListener(this);
    	
    	//Set the Size of the frame    	
    	setSize(WIDTH, HEIGHT);
      
    	// Create a new instance of the WindowDestroyer class
        addWindowListener(new WindowDestroyer( ));
        setTitle("GUI Assignment");
        Container content = getContentPane( );

        
        // Arrange the buttons on the GUI in a Flow Layout
        content.setLayout(new FlowLayout());
             
        // Set up the required buttons on the GUI and the corresponding listener for that action.
        JButton button1 = new JButton("Add Book");
        content.add(button1);
        button1.addActionListener(this); 
        
        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("Highest Price Paid");
        content.add(button4);
        button4.addActionListener(this);
        
        }
    
   /**
    * These methods perform the corresponding action when the buttons on the GUI are clicked.
    * Exception handling in these methods ensure the correct values are entered.  If not, the 
    * user is prompted to re-enter the data correctly.
    * 
    * @param e holds the event that was fired.
    */
    public void actionPerformed(ActionEvent e)
    {
    	if (e.getActionCommand().equals("Add Book"))
        {    
    	   Book book = new Book("", "", 0, "", 0);
    	   title = JOptionPane.showInputDialog("Title");
           author = JOptionPane.showInputDialog("Author");
           publisher = JOptionPane.showInputDialog("Publisher");
        
           do{
              try 
              { 
        	     cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
        	     book.setCost(cost);
        	     goodInput = true;
        	  } 
              catch (Exception cE){          
                 JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for cost");
        	  } 
           }while (!goodInput);

  	       goodInput = false;
           do{
               try 
               { 
         	     year = Integer.parseInt(JOptionPane.showInputDialog("Year"));
         	     book.setYear(year);
         	     goodInput = true;
         	  } 
               catch (Exception yE){          
                  JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for year");
         	  } 
            }while (!goodInput);
           
            //Add an instance of book to the ArrayList
            bookShelf.addBook(book);
        	
            String message =  "The Title of the book is " + title 
                           +  " the Author of the Book is "  + author 
                           + " it's published by " + publisher 
                           + " in " + year
                           + " and it costs " + cost + " euro ";
            JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
        }
        else if (e.getActionCommand().equals("Size of BookShelf")) 
        {
           String message = "The book shelf has " + bookShelf.sizeOfBookshelf() + " book(s)";
           JOptionPane.showMessageDialog(this, message);
        }
        else if (e.getActionCommand().equals("Cost of BookShelf")) 
        {
           String message = "The book shelf value is " + bookShelf.costOfBookShelf() + "Euro";
           JOptionPane.showMessageDialog(this, message);
        }
    	else if (e.getActionCommand().equals("Info"))
        {
        	JOptionPane.showMessageDialog(this, "Tony O'Keeffe - GUI Assignment One");
        }
        else if (e.getActionCommand().equals("Highest Price Paid"))
        {          
            String message = "The highest price paid for a book is: " + bookShelf.highestPricePaid() + "Euro";
            JOptionPane.showMessageDialog(this, message);
        } 
        else
        {
            System.exit( 0 );
        }
    	
     } // end actionPerformed

} //end BookGUI class

Open in new window

0
 
for_yanCommented:
No.
One obvious thing - if you have a class named Insert
then you can have a constructor named

Insert()  <--- name of method exactly the sameas name of class -- very specuial method constructor -- does not require return type

and then you use

new Insert()

to call this constructor and make instamce
of your class

if you have a mettod

public void Insert() {


}

this requires return type - ordinary method and it
is aclled as instance method without new

Pleae, look once again at your code  - you method void Insert()
but you call it as constructor  new Insert() -
makes no sense

Ingeneral classes should start with capital letter
and constructors also - identiacl with class name

methods should start wity lower case -

this is all very good practice - would avoid such mistakes
and of course the main thing logic -

new instantiate instance of class, method executes on that instance




 
0
 
for_yanCommented:

method

void Insert()

does not create any entiy of any type therefore

Insert in = new Insert()

makes no logical sense
0
 
for_yanCommented:


Please, have a look at how I modified your code.
I didn't delete, but rather commented out parts of your original code
so that you could see what was removed.

As you see, main () method
has just initialization - call to the constructor and nothing else,
most of the work is done
in the constructor.
Yes, you can have a special method
specifically for making insert into the database,
which you can call say from the constructor.



You don't need to have Connection and Statement
variables as instance variables: connection variable  is
used only within the constructor, so it can be defiined
in the constructor as local variable.
Statement is also used in the insertRow()
method, but you can pass Statement object
to the insertRow() method as a parameter, as I did.

I also added printStackTrace() methods
inside all catch exception braces, as this is a good parctice -
if there is exception it will
give you the report with the exact line number,
where the problem occured.

 
For some small programs which just store, say, contents
of the file to the database, it is not uncommon that
most of their activity happens in the constructor, sometimes
even exclusivley in the constructor (in fact you also could just put contents
of you method insertRow() into constructor).

For the interactive programs with the user interface, on the other hand,
the constructor is mostly the place where just the preliminary
work of creation and set up of all visual elements is accomplished,
whereas most of the activity is happening in the methods
which are called in response to different events (say, clicking the mouse,
or typing in the textbox of the interface).

In either case, however, the main() method is mostly
used just to call the constructor and, if necessary, read and communicate
to the constructor, i.e. to the program, the command line arguments
(those which are type after java myclass .... on the command line).

Let me know if you have any further questions.
 




package database;

import java.sql.*;


public class Insert {

	//Connection link;
	//Statement statement;
	//ResultSet results;


	public static void main(String[] args){

        new Insert();
    }



		public Insert() {

		 Connection link;
	Statement statement;

		try{
			//Step 1
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			//Step 2
			link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
			statement = link.createStatement();

                    	insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0, statement);
            //
            // in fact you'll probably call many times insert method to insert many rows
          //          you can in future use PreparedStatement, especially if you need multiple inserts



            link.close();

		//	System.out.println("linl: " + link);



			// System.out.println("statn: " + statement);

		}
		catch(ClassNotFoundException e){
			System.out.println("Unable to load driver");
            e.printStackTrace();
			System.exit(1);
		}
		catch(SQLException e){
			System.out.println("Cannot connect to the database");
            e.printStackTrace();
			System.exit(1);
		}   catch (Exception ex){
            
            System.out.println("Error " + ex.toString());
            ex.printStackTrace();
            
        }

            
		//new Insert();
            
         System.exit(0);
	}



	//{
//		try
//		{
//
//			insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0);
//
//		}
//		catch (SQLException e)
//		{
//			System.out.println("Message: " + e.getMessage());
//			System.out.println("SQL State: " + e.getSQLState());
//			System.out.println("SQL Error Code: " + e.getErrorCode());
//			e.printStackTrace();
//			System.exit(1);
//		}
//
//	}


	public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost, Statement statement) throws SQLException

	{
		  String insert = "INSERT INTO BookShelf"
              + " VALUES (" + ID   + ", "
                            + "'" + Title + "', "
                            + "'" + Author   + "','"
                            + Publisher + "', " + Year +"," +  Cost   + ")";

  System.out.println(insert);

  //System.out.println("statn: " + statement);



	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       {
	    	  System.out.println("Failed to insert the following data: "
	    			         + ID   + ","
                             + Title + ","
                             + Author   + ","
                             + Publisher   + ","
                             + Year   + ","
                             + Cost);
	  }

	//link.close();

	//new Insert();


	  }
}

Open in new window

0
 
t38Author Commented:
for_yan, thanks again for the advice and i follow what you are saying but your code above names the class Insert whilst my code's class is BookGUI so if I implement your changes into my code I can't have a class called Insert and I immediately get errors on new Insert(); - 'cannot be resolved to a type' also, if I remove 'class' from public 'public class Insert' Eclipse gives an error - 'return type for the method is missing'.  Am I missing something?
0
 
t38Author Commented:
here's the code as i edited it to fit into mine..
package database;

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener; 
import java.sql.*;

	/**
	 * This class operates as the graphical user interface that interacts with the 
	 * Book and BookShelf classes to add Books to the array and return 
	 * a graphical representation of information from the BookShelf methods.  
	 * 
	 * 
	 */

public class BookGUI extends JFrame implements ActionListener
{
	// Declare the instance variables for the class
	private String title  = "";
	private String author  = "";
	private String publisher  = "";
	private int year = 0;
	private double cost = 0;
    private boolean goodInput = false;
    
	
	// Define the exact dimensions of the graphical interface
    private static final int WIDTH = 600;
   	private static final int HEIGHT = 90;
   	private BookShelf bookShelf;


	//Connection link;
	//Statement statement;
	//ResultSet results;


	public static void main(String[] args){

		BookGUI gui = new BookGUI( );
	       gui.setVisible(true);

		
		new Insert();
    }



		public Insert() {

		 Connection link;
	Statement statement;

		try{
			//Step 1
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			//Step 2
			link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
			statement = link.createStatement();

                    	insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0, statement);
            //
            // in fact you'll probably call many times insert method to insert many rows
          //          you can in future use PreparedStatement, especially if you need multiple inserts



            link.close();

		//	System.out.println("linl: " + link);



			// System.out.println("statn: " + statement);

		}
		catch(ClassNotFoundException e){
			System.out.println("Unable to load driver");
            e.printStackTrace();
			System.exit(1);
		}
		catch(SQLException e){
			System.out.println("Cannot connect to the database");
            e.printStackTrace();
			System.exit(1);
		}   catch (Exception ex){
            
            System.out.println("Error " + ex.toString());
            ex.printStackTrace();
            
        }

            
		//new Insert();
            
         System.exit(0);
	}



	//{
//		try
//		{
//
//			insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0);
//
//		}
//		catch (SQLException e)
//		{
//			System.out.println("Message: " + e.getMessage());
//			System.out.println("SQL State: " + e.getSQLState());
//			System.out.println("SQL Error Code: " + e.getErrorCode());
//			e.printStackTrace();
//			System.exit(1);
//		}
//
//	}


	public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost, Statement statement) throws SQLException

	{
		  String insert = "INSERT INTO BookShelf"
              + " VALUES (" + ID   + ", "
                            + "'" + Title + "', "
                            + "'" + Author   + "','"
                            + Publisher + "', " + Year +"," +  Cost   + ")";

  System.out.println(insert);

  //System.out.println("statn: " + statement);



	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       {
	    	  System.out.println("Failed to insert the following data: "
	    			         + ID   + ","
                             + Title + ","
                             + Author   + ","
                             + Publisher   + ","
                             + Year   + ","
                             + Cost);
	  }

	//link.close();

	//new Insert();


	  }
 
/**
 * Create the GUI frame with buttons and listeners
 */
public BookGUI( )
{
    // Create a new instance of BookShelf	
	bookShelf = new BookShelf();
	
    JFrame frame = this; 
 	
    // Create the main frame's menu bar.
    JMenuBar menubar = new JMenuBar();
	frame.setJMenuBar(menubar);
	frame.pack();
	frame.setVisible(true);
	
	//  Create the File menu
	JMenu fileMenu = new JMenu("File");
	menubar.add(fileMenu);
	
	// Create a Quit option on the File menu
	JMenuItem quitItem = new JMenuItem("Quit");
	fileMenu.add(quitItem);
	quitItem.addActionListener(this); 
	
	// create the About menu
	JMenu aboutMenu = new JMenu ("About");
	menubar.add(aboutMenu);
	
	JMenuItem infoItem = new JMenuItem("Info");
	aboutMenu.add(infoItem);
	infoItem.addActionListener(this);
	
	//Set the Size of the frame    	
	setSize(WIDTH, HEIGHT);
  
	// Create a new instance of the WindowDestroyer class
    addWindowListener(new WindowDestroyer( ));
    setTitle("GUI Assignment");
    Container content = getContentPane( );

    
    // Arrange the buttons on the GUI in a Flow Layout
    content.setLayout(new FlowLayout());
         
    // Set up the required buttons on the GUI and the corresponding listener for that action.
    JButton button1 = new JButton("Add Book");
    content.add(button1);
    button1.addActionListener(this); 
    
    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("Highest Price Paid");
    content.add(button4);
    button4.addActionListener(this);
    
    }

/**
* These methods perform the corresponding action when the buttons on the GUI are clicked.
* Exception handling in these methods ensure the correct values are entered.  If not, the 
* user is prompted to re-enter the data correctly.
* 
* @param e holds the event that was fired.
*/
public void actionPerformed(ActionEvent e)
{
	if (e.getActionCommand().equals("Add Book"))
    {    
	   Book book = new Book("", "", 0, "", 0);
	   title = JOptionPane.showInputDialog("Title");
       author = JOptionPane.showInputDialog("Author");
       publisher = JOptionPane.showInputDialog("Publisher");
    
       do{
          try 
          { 
    	     cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
    	     book.setCost(cost);
    	     goodInput = true;
    	  } 
          catch (Exception cE){          
             JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for cost");
    	  } 
       }while (!goodInput);

	       goodInput = false;
       do{
           try 
           { 
     	     year = Integer.parseInt(JOptionPane.showInputDialog("Year"));
     	     book.setYear(year);
     	     goodInput = true;
     	  } 
           catch (Exception yE){          
              JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for year");
     	  } 
        }while (!goodInput);
       
        //Add an instance of book to the ArrayList
        bookShelf.addBook(book);
    	
        String message =  "The Title of the book is " + title 
                       +  " the Author of the Book is "  + author 
                       + " it's published by " + publisher 
                       + " in " + year
                       + " and it costs " + cost + " euro ";
        JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
    }
    else if (e.getActionCommand().equals("Size of BookShelf")) 
    {
       String message = "The book shelf has " + bookShelf.sizeOfBookshelf() + " book(s)";
       JOptionPane.showMessageDialog(this, message);
    }
    else if (e.getActionCommand().equals("Cost of BookShelf")) 
    {
       String message = "The book shelf value is " + bookShelf.costOfBookShelf() + "Euro";
       JOptionPane.showMessageDialog(this, message);
    }
	else if (e.getActionCommand().equals("Info"))
    {
    	JOptionPane.showMessageDialog(this, "Tony O'Keeffe - GUI Assignment One");
    }
    else if (e.getActionCommand().equals("Highest Price Paid"))
    {          
        String message = "The highest price paid for a book is: " + bookShelf.highestPricePaid() + "Euro";
        JOptionPane.showMessageDialog(this, message);
    } 
    else
    {
        System.exit( 0 );
    }
	
 } // end actionPerformed

Open in new window

0
 
for_yanCommented:
OK, let me start from this onwe - of course  public class name and java file name should be the same.
And cosntructor name should be exactly like class name.
Strange, I don't rememeber renaming deliberatly - I started form some of your codes
which had class Insert, I believe.

And look, in class BookGUI you cannot have statement like

public Insert() {...}

Why? because if this is a constructor its name should be exavctly like the name of the class

If thios is a regular method then it should have return type , at least void type

-------------------------------
Therefore, let's rememeber that - it is very important - within the
class named A you cannot
have statemnet  
 
public B() {...}

you either have

public A() {...} - constructor

or you have

public void B(){...} - regular method


}
-----------------------------------------



I kind of see that this is different calss altogether - the one I started yesterday from
was not exteniding JFrame.


OK, this is altogether something differnt, than I was editing yesterdauy - I swear you had something without GUI,

So, if you need this one let me look at it again.

0
 
for_yanCommented:

Of course waht I edited yesterday replaced your code in  ID:35444089

So I corrected that and showed you how to write that

And now within the same trail you posted absolutely different program ID:35444480

That's real confusion.

OK, now let me look at this new program

0
 
for_yanCommented:
For me to clean up this code, please post class BookShelf, otherwise I need to invent some stub,
to have compiler happy
0
 
for_yanCommented:

OK, never mind about Book and BookShelf - compiler
will need it but to show you overall picture I don't need it.

So look how I modified the code.

Yes in class BookGUI your constructor should
be called BookGUI()

There cannot be another constructor called Insert()

You already know why - because name of the constructor
always the same as name of the class

So what is the solution here ?

You put the stuff about getting the book from the database into the
same and only constructor which you have - BookGUI().
And it is common practice - if you build the class with GUI
which also relies on populatingthis GUI with some data at the startup - that's
what you do in constructor - usually, first thing you go to database
retrieve your data and then
craete all thise visual elements and if necessary populate them
with already retirieved data (e.g. show some initial
list of books in your JList or in your JTextArea).

In your case you are doing something not so justified logically  - writing the
book to the database form the very start of your program - that
will be strandge from the point of view of general logic of the program,
but still perfectly OK from
the point of view of the overall organization
of the Java code - so in you constructor
you first deal with databse issues (maybe calling some instance
method in the procsess, like you do) and then in the same constructor you
create visual elements.

As before main() jsut contains creation of  the instance - call to the constructor



package database;

import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.sql.*;

	/**
	 * This class operates as the graphical user interface that interacts with the
	 * Book and BookShelf classes to add Books to the array and return
	 * a graphical representation of information from the BookShelf methods.
	 *
	 *
	 */

public class BookGUI extends JFrame implements ActionListener
{
	// Declare the instance variables for the class
	private String title  = "";
	private String author  = "";
	private String publisher  = "";
	private int year = 0;
	private double cost = 0;
    private boolean goodInput = false;


	// Define the exact dimensions of the graphical interface
    private static final int WIDTH = 600;
   	private static final int HEIGHT = 90;
   	private BookShelf bookShelf;


	//Connection link;
	//Statement statement;
	//ResultSet results;


	public static void main(String[] args){

		BookGUI gui = new BookGUI( );
	       gui.setVisible(true);


    }





	//{
//		try
//		{
//
//			insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0);
//
//		}
//		catch (SQLException e)
//		{
//			System.out.println("Message: " + e.getMessage());
//			System.out.println("SQL State: " + e.getSQLState());
//			System.out.println("SQL Error Code: " + e.getErrorCode());
//			e.printStackTrace();
//			System.exit(1);
//		}
//
//	}


	public void insertRow(int ID, String Title, String Author, String Publisher, int Year, double Cost, Statement statement) throws SQLException

	{
		  String insert = "INSERT INTO BookShelf"
              + " VALUES (" + ID   + ", "
                            + "'" + Title + "', "
                            + "'" + Author   + "','"
                            + Publisher + "', " + Year +"," +  Cost   + ")";

  System.out.println(insert);

  //System.out.println("statn: " + statement);



	       int result = statement.executeUpdate(insert);
	       if (result == 0)
	       {
	    	  System.out.println("Failed to insert the following data: "
	    			         + ID   + ","
                             + Title + ","
                             + Author   + ","
                             + Publisher   + ","
                             + Year   + ","
                             + Cost);
	  }

	//link.close();

	//new Insert();


	  }

/**
 * Create the GUI frame with buttons and listeners
 */
public BookGUI( )   {

    Connection link;
   Statement statement;

    try{
        //Step 1
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        //Step 2
        link = DriverManager.getConnection("jdbc:odbc:BookShelf","","");
        statement = link.createStatement();

                    insertRow(28, "Test Five", "Stephen King", "Publish", 2000, 20.0, statement);
        //
        // in fact you'll probably call many times insert method to insert many rows
      //          you can in future use PreparedStatement, especially if you need multiple inserts



        link.close();

    //	System.out.println("linl: " + link);



        // System.out.println("statn: " + statement);

    }
    catch(ClassNotFoundException e){
        System.out.println("Unable to load driver");
        e.printStackTrace();
        System.exit(1);
    }
    catch(SQLException e){
        System.out.println("Cannot connect to the database");
        e.printStackTrace();
        System.exit(1);
    }   catch (Exception ex){

        System.out.println("Error " + ex.toString());
        ex.printStackTrace();

    }





    // Create a new instance of BookShelf
	bookShelf = new BookShelf();

    JFrame frame = this;

    // Create the main frame's menu bar.
    JMenuBar menubar = new JMenuBar();
	frame.setJMenuBar(menubar);
	frame.pack();
	frame.setVisible(true);

	//  Create the File menu
	JMenu fileMenu = new JMenu("File");
	menubar.add(fileMenu);

	// Create a Quit option on the File menu
	JMenuItem quitItem = new JMenuItem("Quit");
	fileMenu.add(quitItem);
	quitItem.addActionListener(this);

	// create the About menu
	JMenu aboutMenu = new JMenu ("About");
	menubar.add(aboutMenu);

	JMenuItem infoItem = new JMenuItem("Info");
	aboutMenu.add(infoItem);
	infoItem.addActionListener(this);

	//Set the Size of the frame
	setSize(WIDTH, HEIGHT);

	// Create a new instance of the WindowDestroyer class
    addWindowListener(new WindowDestroyer( ));
    setTitle("GUI Assignment");
    Container content = getContentPane( );


    // Arrange the buttons on the GUI in a Flow Layout
    content.setLayout(new FlowLayout());

    // Set up the required buttons on the GUI and the corresponding listener for that action.
    JButton button1 = new JButton("Add Book");
    content.add(button1);
    button1.addActionListener(this);

    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("Highest Price Paid");
    content.add(button4);
    button4.addActionListener(this);



/**
* These methods perform the corresponding action when the buttons on the GUI are clicked.
* Exception handling in these methods ensure the correct values are entered.  If not, the
* user is prompted to re-enter the data correctly.
*
* @param e holds the event that was fired.
*/
public void actionPerformed(ActionEvent e)
{
	if (e.getActionCommand().equals("Add Book"))
    {
	   Book book = new Book("", "", 0, "", 0);
	   title = JOptionPane.showInputDialog("Title");
       author = JOptionPane.showInputDialog("Author");
       publisher = JOptionPane.showInputDialog("Publisher");

       do{
          try
          {
    	     cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
    	     book.setCost(cost);
    	     goodInput = true;
    	  }
          catch (Exception cE){
             JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for cost");
    	  }
       }while (!goodInput);

	       goodInput = false;
       do{
           try
           {
     	     year = Integer.parseInt(JOptionPane.showInputDialog("Year"));
     	     book.setYear(year);
     	     goodInput = true;
     	  }
           catch (Exception yE){
              JOptionPane.showMessageDialog(this, "Numerical entry required. Please re-enter a value for year");
     	  }
        }while (!goodInput);

        //Add an instance of book to the ArrayList
        bookShelf.addBook(book);

        String message =  "The Title of the book is " + title
                       +  " the Author of the Book is "  + author
                       + " it's published by " + publisher
                       + " in " + year
                       + " and it costs " + cost + " euro ";
        JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
    }
    else if (e.getActionCommand().equals("Size of BookShelf"))
    {
       String message = "The book shelf has " + bookShelf.sizeOfBookshelf() + " book(s)";
       JOptionPane.showMessageDialog(this, message);
    }
    else if (e.getActionCommand().equals("Cost of BookShelf"))
    {
       String message = "The book shelf value is " + bookShelf.costOfBookShelf() + "Euro";
       JOptionPane.showMessageDialog(this, message);
    }
	else if (e.getActionCommand().equals("Info"))
    {
    	JOptionPane.showMessageDialog(this, "Tony O'Keeffe - GUI Assignment One");
    }
    else if (e.getActionCommand().equals("Highest Price Paid"))
    {
        String message = "The highest price paid for a book is: " + bookShelf.highestPricePaid() + "Euro";
        JOptionPane.showMessageDialog(this, message);
    }
    else
    {
        System.exit( 0 );
    }

 } // end actionPerformed

}

Open in new window

0
 
t38Author Commented:
Hi Sorry about the confusion, I accidentally used the 'old' code in one of my posts, please see BookShelf code below.
package database;
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.
  *
  *
  * 
  */

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
 
for_yanCommented:


See my previous post - it would need both BookShelf and Book for me to really compile it.
But I probably don't need to fully compile it at least at this point - I modified it
to show you general structure - and explained it above. Please, read, and let me know if you have
any questions

0
 
t38Author Commented:
Thanks for all your help that really helps explain it for me and I understand the class database interaction much moreso now.
0
 
for_yanCommented:
You are always welcome.
I'm happy you are now understanding this stuff more clear.
0

Featured Post

Technology Partners: 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!

  • 20
  • 12
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now