Results 1 to 20 of 20
  1. #1
    Taz_84 is offline Member
    Join Date
    May 2008
    Posts
    7
    Rep Power
    0

    Default non-static method cannot be referenced

    Hi,

    I am new to java (as you probably already guessed). I am creating a program that simply reads liquor list from a txt file. I have implemented most of the codes and when i implemented the GUI and referenced the initGui() method from inside the main method it gives me an error : LiquorRecordSystem.java:47: non-static method initGui() cannot be referenced from a static context initGui();

    I have no idea what this error is saying let alone fixing it. I would really appreciate a helping hand to fix this problem. my coding is below, thanking you in advance.

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.io.*;
    
    public class LiquorRecordSystem extends JFrame
    {
    	static LinkedList liquorList = new LinkedList();
    	public  static void main (String [] args)
    	{
    
    		loadData();
    
    		// display screen
    		initGui();
    		controlPanel();
    
    	}//static
    
    	public void initGui()
    	{
    
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setResizable(false);
    		setSize(FRAME_WIDTH,FRAME_HEIGHT);
    		setVisible(true);
    
    
    	}//inintGui()
    
    	public void controlPanel()
    	{
    
    		//Panels
    
    		JPanel textAreaPanel = createTextAreaPanel();
    		JPanel labelPanel = createLabelPanel();
    		JPanel buttonPanel = createButtonPanel();
    
    
    		//topPanel
    
    		JPanel topPanel = new JPanel ();
    		topPanel.setLayout (new FlowLayout());
    		topPanel.add(textAreaPanel);
    
    		//CenterPanel
    		JPanel centerPanel = new JPanel();
    		centerPanel.setLayout (new FlowLayout());
    		centerPanel.add(labelPanel);
    
    		//bottomPanel
    		JPanel bottomPanel = new JPanel ();
    		bottomPanel.setLayout(new FlowLayout());
    		bottomPanel.add(buttonPanel);
    
    
    		add(topPanel);
    		add(centerPanel);
    		add(bottomPanel);
    
    	}//controlPanel()
    
    
    	public JPanel createTextAreaPanel()
    	{
    		textArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
    		textArea.setEditable(false);
    
    		JPanel panel = new JPanel();
    		panel.add(textArea);
    
    		return panel;
    	}//createTextAreaPanel()
    
    
    	public JPanel createLabelPanel()
    	{
    
    		//TextField Labels
    		liquorIdLabel = new JLabel ("LiquorID");
    		descLabel = new JLabel ("Description");
    		priceLabel = new JLabel ("Price");
    		amountLabel = new JLabel ("Amount");
    
    
    		//TextField
    
    		liquorIdTextField = new JTextField(4);
    		descTextField = new JTextField(10);
    		priceTextField = new JTextField(5);
    		amountTextField = new JTextField(5);
    
    
    		JPanel panel = new JPanel ();
    		panel.add(liquorIdLabel);
    		panel.add(liquorIdTextField);
    		panel.add(descLabel);
    		panel.add(descTextField);
    		panel.add(priceLabel);
    		panel.add(priceTextField);
    		panel.add(amountLabel);
    		panel.add(amountTextField);
    
    		return panel;
    	}//createLabelPanel()
    
    
    	public JPanel createButtonPanel()
    	{
    		addButton = new JButton ("Add");
    		//listener required
    
    		removeButton = new JButton ("Remove");
    		//listener required
    
    		updateButton = new JButton ("Update");
    		//listener required
    
    		saveButton = new JButton ("Save");
    		//listener required
    
    		JPanel panel = new JPanel ();
    		panel.add(addButton);
    		panel.add(removeButton);
    		panel.add(updateButton);
    		panel.add(saveButton);
    
    
    		return panel;
    
    	}//createButtonpanel()
    
    	//	Labels
    
    	//	JLabel
    
    	//	TextFields
    
    	//	Buttons
    
    	//	TextArea
    
    
    		// create and load screen
    		//  update view
    
    
    
    	private static void loadData( )
    	{
    	   try {
    
    		   BufferedReader in=new BufferedReader(new
                         FileReader("LiquorEntry.txt"));
    
    		   String myEntry;
    
    		   String description="";
    		   int id=1000, amount=1;
    		   double price=0.0;
    
    		   while((myEntry=in.readLine())!=null)
    		   {
    			StringTokenizer st=new StringTokenizer(myEntry);
    
    			while(st.hasMoreTokens())
    			{
    			   id=Integer.parseInt((st.nextToken()));
    			   description=st.nextToken();
    			   price=Double.parseDouble(st.nextToken());
    		       amount=Integer.parseInt(st.nextToken());
                   Liquor myLiquor = new Liquor(id, description,price,amount);
                   liquorList.addLast(myLiquor);
    			}
    
    		   }// end of while loop
    		    in.close();
    	      } catch(FileNotFoundException e) {
    			  	return;
              } catch(IOException ex){
    	        	System.out.println("file loading failed.");
              }
           }//end of the method
    
    	 class AddActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			int id = Integer.parseInt(liquorIdTextField.getText());
    			// get description, price, amount from text fields
    			// create new Liquor object;
    			// add to the list
    
    			// update display of the list and clear text fields
    
    		}
    	}
    
    	class RemoveActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			ListIterator itr = liquorList.listIterator();
    			while (itr.hasNext()) {
    				Liquor li = (Liquor)itr.next();
    				if (li.getId() == Integer.parseInt(liquorIdTextField.getText())) {
    					itr.remove();
    					break;
    					// in case of update set desc, price and amount to Liquor
    				}
    			}
    			int id = Integer.parseInt(liquorIdTextField.getText());
    
    			// update display of the list and clear text fields
    
    		}
    
    	}
    	 class UpdateActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    
    			ListIterator itr = liquorList.listIterator();
    			String fileContent = "";
    			while (itr.hasNext()) {
    				Liquor li = (Liquor)itr.next();
    				fileContent = fileContent + li + "\n\r";
    			}
    
    			// write fileContent to the file;
    
    		}
    
    	}
    
    	public void updateView()
    	{
    		for(int i = 0; i < liquorList.size(); i++)
    		{
    			textArea.append(liquorList.get(i).toString());
    		}
    
    		textArea.append("Total:" + liquorList.size() + " Liquor entries");
    
    	}
    
    
    
    
    	private JTextArea textArea;
    
    	private JLabel liquorIdLabel;
    	private JLabel descLabel;
    	private JLabel priceLabel;
    	private JLabel amountLabel;
    
    	private JTextField liquorIdTextField;
    	private JTextField descTextField;
    	private JTextField priceTextField;
    	private JTextField amountTextField;
    
    	private JButton addButton;
    	private JButton removeButton;
    	private JButton updateButton;
    	private JButton saveButton;
    
    	private static final int AREA_ROWS = 20;
    	private static final int AREA_COLUMNS = 30;
    
    	private static final int FRAME_WIDTH = 500;
    	private static final int FRAME_HEIGHT = 400;
    }//class

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    One of the beauties of the Java programming language is that it can be used to create Object-Oriented Programs (OOPs), where classes can be used to create objects, and objects can interact with each other in ways that at times can mimic the real world.

    In order to create an OOPs program and to call an object's methods, you first have to create an object, and that is what is missing here. I think that your main method should first and foremost create a LiquorRecordSystem object, and then call the methods you are having trouble with on this object. In fact the other method, loadData, should probably be a non-static method and it too should be called on the object. In fact you should probably rid that program of the word "static", everything except of course the main method which must be static.

    I recommend that you have a look at the Sun Java tutorial regarding what objects and classes are and how to use them:
    Lesson: Object-Oriented Programming Concepts (The Java™ Tutorials > Learning the Java Language)

    Wishing much luck!

  3. #3
    Taz_84 is offline Member
    Join Date
    May 2008
    Posts
    7
    Rep Power
    0

    Default

    Thanks very much Fubarable. I'll work on it now and let you know how I went. fingers crossed no more problems, had enough of it!

    thanks again

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I have found some other problems in your code:

    Java Code:
    public class LiquorRecordSystem extends JFrame
    {
      LinkedList<Liquor> liquorList = new LinkedList<Liquor>();
    
      public static void main(String[] args)
      {
        LiquorRecordSystem recordSys = new LiquorRecordSystem();
        recordSys.loadData();
    
        // display screen
        recordSys.controlPanel();
        recordSys.initGui();//!! swap these guys
    
      }//static
    You'll want to make your linked list a generic list by adding <Liquor> (if you're using Java 5 or 6 to compile it). This will add compile time type checking and will make the program easier to debug and maintain.

    You'll want to swap the order you call controlPanel and initGui as you'll want to add the widgets first before making the GUI visible.

    Java Code:
      public void initGui()
      {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        //setSize(FRAME_WIDTH, FRAME_HEIGHT);
        pack(); //!! add pack
        setVisible(true);
    
      }//inintGui()
    Your current size is too small to show everything. Better to make it bigger. Better still is to just pack the JFrame and let the layout managers decide on what the optimal size should be.

    Java Code:
      private void loadData() // removed "static" modifier
      {
        try
        {
          BufferedReader in = new BufferedReader(new FileReader("LiquorEntry.txt"));
    
          //..... etc
    
          in.close();
        }
        catch (FileNotFoundException e)
        {
          return;  //!! unhandled exception
        }
        catch (IOException ex)
        {
          System.out.println("file loading failed.");
        }
      }
    You don't deal with a caught exception where I indicated with "unhandled exception" and this is a bad thing to do. Your users will not like you if the program fails and they don't know why. At least print a stack trace here.

    Also, you should close the BufferedReader in the finally block so that it is guaranteed to close. I usually check that it's not null before closing it.

    Best of luck and hope this helps.

  5. #5
    Taz_84 is offline Member
    Join Date
    May 2008
    Posts
    7
    Rep Power
    0

    Default

    Fubarable thank you very much for those replies. with your help i managed to get up to getting the GUI up and running. My new problem is the data is not passing from the txt file to the textArea. Could you please help?

    thank you very much i really appreciate your time.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    post your latest code and your text files.

  7. #7
    Taz_84 is offline Member
    Join Date
    May 2008
    Posts
    7
    Rep Power
    0

    Default

    Fubarable, thank you for your reply. codes as follows

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.io.*;
    
    public class LiquorRecordSystem extends JFrame
    {
    
    	LinkedList<Liquor> liquorList = new LinkedList<Liquor>();
    
    	public  static void main (String [] args)
    	{
    
    
    		LiquorRecordSystem lrs = new LiquorRecordSystem ();
    
    		lrs.loadData();
    
    		// display screen
    		lrs.controlPanel();
    		lrs.initGui();
    
    
    	}//static
    
    	public void initGui()
    	{
    
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setResizable(false);
    		pack();
    		setVisible(true);
    
    
    	}//inintGui()
    
    	public void controlPanel()
    	{
    
    		//Panels
    
    		JPanel textAreaPanel = createTextAreaPanel();
    		JPanel labelPanel = createLabelPanel();
    		JPanel buttonPanel = createButtonPanel();
    
    
    		//topPanel
    
    		JPanel topPanel = new JPanel ();
    		topPanel.setLayout (new FlowLayout());
    		topPanel.add(textAreaPanel);
    
    		//CenterPanel
    		JPanel centerPanel = new JPanel();
    		centerPanel.setLayout (new FlowLayout());
    		centerPanel.add(labelPanel);
    
    		//bottomPanel
    		JPanel bottomPanel = new JPanel ();
    		bottomPanel.setLayout(new FlowLayout());
    		bottomPanel.add(buttonPanel);
    
    
    		add(topPanel, BorderLayout.NORTH);
    		add(centerPanel, BorderLayout.CENTER);
    		add(bottomPanel, BorderLayout.SOUTH);
    
    	}//controlPanel()
    
    
    	public JPanel createTextAreaPanel()
    	{
    		textArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
    		//textArea.setLayout(new BorderLayout());
    		textArea.setEditable(false);
    
    		JPanel panel = new JPanel();
    		panel.add(textArea);
    
    		return panel;
    	}//createTextAreaPanel()
    
    
    	public JPanel createLabelPanel()
    	{
    
    		//TextField Labels
    		liquorIdLabel = new JLabel ("LiquorID");
    		descLabel = new JLabel ("Description");
    		priceLabel = new JLabel ("Price");
    		amountLabel = new JLabel ("Amount");
    
    
    		//TextField
    
    		liquorIdTextField = new JTextField(4);
    		descTextField = new JTextField(10);
    		priceTextField = new JTextField(5);
    		amountTextField = new JTextField(5);
    
    
    		JPanel panel = new JPanel ();
    		panel.add(liquorIdLabel);
    		panel.add(liquorIdTextField);
    		panel.add(descLabel);
    		panel.add(descTextField);
    		panel.add(priceLabel);
    		panel.add(priceTextField);
    		panel.add(amountLabel);
    		panel.add(amountTextField);
    
    		return panel;
    	}//createLabelPanel()
    
    
    	public JPanel createButtonPanel()
    	{
    		addButton = new JButton ("Add");
    		//listener required
    
    		removeButton = new JButton ("Remove");
    		//listener required
    
    		updateButton = new JButton ("Update");
    		//listener required
    
    		saveButton = new JButton ("Save");
    		//listener required
    
    		JPanel panel = new JPanel ();
    		panel.add(addButton);
    		panel.add(removeButton);
    		panel.add(updateButton);
    		panel.add(saveButton);
    
    
    		return panel;
    
    	}//createButtonpanel()
    
    
    
    
    
    	private void loadData( )
    	{
    	   try {
    
    		   BufferedReader in=new BufferedReader(new
                         FileReader("liquorentry.txt"));
    
    		   String myEntry;
    
    		   String description="";
    		   int id=1000, amount=1;
    		   double price=0.0;
    
    		   while((myEntry=in.readLine())!=null)
    		   {
    			StringTokenizer st=new StringTokenizer(myEntry);
    
    			while(st.hasMoreTokens())
    			{
    			   id=Integer.parseInt((st.nextToken()));
    			   description=st.nextToken();
    			   price=Double.parseDouble(st.nextToken());
    		       amount=Integer.parseInt(st.nextToken());
                   Liquor myLiquor = new Liquor(id, description,price,amount);
                   liquorList.addLast(myLiquor);
    			}
    
    		   }// end of while loop
    		    in.close();
    	      } catch(FileNotFoundException ex) {
    			  	System.out.println("File not found");
              } catch(IOException ex){
    	        	System.out.println("File loading failed.");
              }
    
    
              display();
           }//end of the method
    
    
           //////////////////////////////////////listeners
    
    	class AddActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			int id = Integer.parseInt(liquorIdTextField.getText());
    			String desc = descTextField.getText();
    			double price = Double.parseDouble(priceTextField.getText());
    			int amount = Integer.parseInt(amountTextField.getText());
    
    			// get description, price, amount from text fields
    			// create new Liquor object;
    			// add to the list
    
    			ListIterator itr = liquorList.listIterator();
    			String fileContent = "";
    			Liquor li = (Liquor)itr.next();
    			fileContent = fileContent + li + "\n\r";
    
    			// update display of the list and clear text fields
    			updateView();
    		}
    		
    		
    	}//addActionListener
    
    	class RemoveActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			ListIterator itr = liquorList.listIterator();
    			while (itr.hasNext()) {
    				Liquor li = (Liquor)itr.next();
    				if (li.getId() == Integer.parseInt(liquorIdTextField.getText())) {
    					itr.remove();
    					break;
    					// in case of update set desc, price and amount to Liquor
    				}
    			}
    			int id = Integer.parseInt(liquorIdTextField.getText());
    
    			// update display of the list and clear text fields
    
    		}
    
    	}
    	 class UpdateActionListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    
    			ListIterator itr = liquorList.listIterator();
    			String fileContent = "";
    			while (itr.hasNext()) {
    				Liquor li = (Liquor)itr.next();
    				fileContent = fileContent + li + "\n\r";
    			}
    
    			// write fileContent to the file;
    
    		}
    
    	}
    
    	public void updateView()
    	{
    		for(int i = 0; i < liquorList.size(); i++)
    		{
    			textArea.append(liquorList.get(i).toString());
    		}
    
    		textArea.append("Total:" + liquorList.size() + " Liquor entries");
    
    	}
    
    
    
    	public void display()
    	{
    		for (int i = 0; i <liquorList.size(); i++)
    		{
    
    		textArea.append(liquorList.get(i).toString());
    		}
    	}
    
    
    
    	private JTextArea textArea;
    
    	private JLabel liquorIdLabel;
    	private JLabel descLabel;
    	private JLabel priceLabel;
    	private JLabel amountLabel;
    
    	private JTextField liquorIdTextField;
    	private JTextField descTextField;
    	private JTextField priceTextField;
    	private JTextField amountTextField;
    
    	private JButton addButton;
    	private JButton removeButton;
    	private JButton updateButton;
    	private JButton saveButton;
    
    
    	private static final int AREA_ROWS = 20;
    	private static final int AREA_COLUMNS = 30;
    
    	private static final int FRAME_WIDTH = 600;
    	private static final int FRAME_HEIGHT = 450;

    Text File:
    Java Code:
    1001 Jacob-Merlot01 8.0 10
    5001 Tooheys-MID07 35.99 70
    5002 Fosters-Light 29.99 50
    2003 Dewar's-White 25.55 30
    2004 Chivas-Regal 30.0 45
    Java Code:
    public class Liquor
    {
    	private int id;
    	private String desc;
    	private double price;
    	private int amount;
    
    	public Liquor()
    	{
    	}
    	public Liquor(int theId, String theDesc, double thePrice, int theAmount)
    	{
    		this.id = theId;
    		this.desc = theDesc;
    		this.price = thePrice;
    		this.amount = theAmount;
    
    	}
    
    	public int getId()
    	{
    		return this.id;
    
    	}
    
    	public void set(int theId)
    	{
    		this.id = theId;
    	}
    
    	public String getDescription()
    	{
    		return this.desc;
    	}
    
    	public void setDscription(String theDesc)
    	{
    		this.desc = theDesc;
    	}
    
    	public double getPrice()
    	{
    		return this.price;
    	}
    
    	public void setPrice(double thePrice)
    	{
    		this.price = thePrice;
    	}
    
    	public int getAmount()
    	{
    		return this.amount;
    	}
    
    	public void setAmount(int theAmount)
    	{
    		this.amount = theAmount;
    	}
    
    	public String toString()
    	{
    		return id + " " + desc + " " + price + " " + amount;
    	}
    }

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Time for some debugging: So what problem is this code causing? What exception or error is being thrown? If so where? if you know where, what on that line is the cause of the exception?

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Well, you have left it appears.

    Some advice: if you see a NPE, you should check every object on the line that throws it to see why the NPE is occurring. If you do it in this situation you will likely see pretty quickly why this is happening -- you're using an object before it has been initialized. Well anyway, good luck.

  10. #10
    Taz_84 is offline Member
    Join Date
    May 2008
    Posts
    7
    Rep Power
    0

    Default

    Fubarable,

    No I haven't left it. There were no errors or anything. it complies perfectly. and it shows the gui. however my expectation is that there should be some text appearing from textfile. but that was not happening. So that was my main problem.

    ps - sorry for the late reply.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    then either the code you posted is not the code you're running, or the code is throwing an exception and you're not seeing it for some reason, because when I compile and run it, a nullpointerexception is thrown, and for good reason too. You may want to double check this and then have a go at some debugging.
    Last edited by Fubarable; 12-29-2008 at 02:31 PM.

  12. #12
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    I think you could create a test class with only the loadData() method to see if your code behaves correctly. Then println() each liquor in your test-class liquorList. If those Liquor are created correctly, then it's probably a GUI problem. But your code is too long... :-) Please post a simplified version

    And, but it's just my opinion, the method for creating the GUI should be private, and all those GUI elements shouldn't be object members, but instead declared in the method body in which are used

    And I think it's better (once your program gets compiled) to show the various Liquor's field in a JTable rather then in a TextArea. Now I'm studying, I hope I'll help you later

    Bye
    Last edited by raffaele181188; 12-29-2008 at 02:56 PM.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by raffaele181188 View Post
    I think you could create a test class with only the loadData() method to see if your code behaves correctly. Then println() each liquor in your test-class liquorList.
    Agree. His does load OK.

    If those Liquor are created correctly, then it's probably a GUI problem. But your code is too long... :-) Please post a simplified version
    Yep, an SSCCE is what is needed here.

    And, but it's just my opinion, the method for creating the GUI should be private, and all those GUI elements shouldn't be object members, but instead declared in the method body in which are used
    with the exceptions being those members that are needed in the class's scope, such as in this instance, the JTextArea.

    And I think it's better (once your program gets compiled) to show the various Liquor's field in a JTable rather then in a TextArea.
    Yep, another great suggestion.

    I think we both agree that most important is to divide and conquer -- to break down the important parts of your program into smaller classes and solve each class's problem in isolation.

  14. #14
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    Hi Fubarable

    I'm working on his classes right now. Soon you'll see SSCCE code

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm thinking that he should be the one creating the SSCCEs ;)

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    and before you waste too much time, please understand that his problem is simply one of calling an object before it has been realized. When he calls display here:
    Java Code:
      private void loadData()
      {
        try
        {
    
          BufferedReader in = new BufferedReader(new FileReader(LIQUOR_TEXT));
    
          // ..........
    
          while ((myEntry = in.readLine()) != null)
          {
    
            // ........
    
          }
          in.close(); // *** again this should be in the finally block ***
        }
        catch (FileNotFoundException ex)
        {
          System.out.println("File not found");
        }
        catch (IOException ex)
        {
          System.out.println("File loading failed.");
        }
    
        display(); // **** here ***
      }
    He's trying to display data in a JTextArea that has not been created nor displayed yet.

    I was trying to nudge the original poster in the direction that would allow him to discover this for himself, but I was somewhat dismayed that he didn't even see the NPE that was being thrown, and I'm not sure why.

  17. #17
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default SSCCE code

    You're right, but I'm a student and I need these things... here is its code

    PLEASE KEEP IN MIND (TO COMPILE):
    1. All the classes belongs to the liquorappdemo package, so place them in the right places
    2. The main() method of LiquorAppDemo requires one command-line argument: the absolute path of the data file

    Try to compile these 2 classes
    For me there is no problem: the classes get compiled and the program shows the GUI, but I think that it's a GUI problem. For safety the main() method prints on standard error the same things that the textArea would show. But I suggest that a JTable is much better to display this sort of data than a JTextArea

    Luck, now I have to go

    Liquor.java
    Java Code:
    package liquorappdemo;
    
    public class Liquor {
    	private int id;
    	private String desc;
    	private double price;
    	private int amount;
    
    	public Liquor(int id, String desc, double price, int amount){
    		this.id = id;
    		this.desc = desc;
    		this.price = price;
    		this.amount = amount;
    	}
    
    	public String toString() {
    		return getId() + ": " + getDesc() + " " + getPrice() +
    				" Quantity: " + getAmount();
    	}
    	
    	//Now setter and getter methods. They are not intersting so I put them
    	//on a single line to save visual space
    	public int getId() { return id;	}
    	public void setId(int id) {	this.id = id; }
    	public String getDesc() { return desc; }
    	public void setDesc(String desc) { this.desc = desc;}
    	public double getPrice() {return price;}
    	public void setPrice(double price) {this.price = price;}
    	public int getAmount() {return amount;}
    	public void setAmount(int amount) {	this.amount = amount;}
    }
    LiquorAppView.java
    Java Code:
    package liquorappdemo;
    
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.io.*;
    
    public class LiquorAppView extends JFrame {
    	private JTextArea textArea;
    
    	//This is the only way to get this view, the constructor is private
    	public static LiquorAppView appear() {
    		return new LiquorAppView();
    	}
    	
    	//This method doesn't work if the argument is null
    	public void refreshData(java.util.List<Liquor> newList) {
    		if (newList == null)
    			throw new NullPointerException();
    		StringBuilder content = new StringBuilder();
    		for (Liquor l : newList){
    			content.append(l.toString() + "\n");
    		}
    		textArea.setText(content.toString());
    	}
    
    	//Now I made this private. To get the view you use the
    	//static method appear() instead, which also shows the GUI
    	private LiquorAppView() {
    		controlPanel();
    		createTextAreaPanel();
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setResizable(false);
    		pack();
    		setVisible(true);
    	}
    	
    	/*************************************************************************
    	 * These are the method to format the GUI.
    	 * 
    	 * HERE IS YOUR ERROR!!!
    	 * 
    	 * However, I cut your application off a lot... Maybe I've done some
    	 * mistakes. But I think this way your code is much clearer. You can start
    	 * here if you want
    	 *  
    	 ************************************************************************/
    	private void controlPanel() {
    		JPanel textAreaPanel = createTextAreaPanel();
    		JPanel labelPanel = createLabelPanel();
    		JPanel buttonPanel = createButtonPanel();
    		//topPanel
    		JPanel topPanel = new JPanel ();
    		topPanel.setLayout (new FlowLayout());
    		topPanel.add(textAreaPanel);
    		//CenterPanel
    		JPanel centerPanel = new JPanel();
    		centerPanel.setLayout (new FlowLayout());
    		centerPanel.add(labelPanel);
    		//bottomPanel
    		JPanel bottomPanel = new JPanel ();
    		bottomPanel.setLayout(new FlowLayout());
    		bottomPanel.add(buttonPanel);
    		add(topPanel, BorderLayout.NORTH);
    		add(centerPanel, BorderLayout.CENTER);
    		add(bottomPanel, BorderLayout.SOUTH);
    	}
    
    
    	private JPanel createTextAreaPanel() {
    		int rows = 20,
    			cols = 30;
    		textArea = new JTextArea(rows, cols);
    		textArea.setEditable(false);
    		JPanel panel = new JPanel();
    		panel.add(textArea);
    		return panel;
    	}
    
    	private JPanel createLabelPanel() {
    		JLabel liquorIdLabel = new JLabel ("LiquorID"),
    				descLabel = new JLabel ("Description"),
    				priceLabel = new JLabel ("Price"),
    				amountLabel = new JLabel ("Amount");
    		JTextField liquorIdTextField = new JTextField(4),
    				descTextField = new JTextField(10),
    				priceTextField = new JTextField(5),
    				amountTextField = new JTextField(4);
    		
    		JPanel panel = new JPanel();
    		panel.add(liquorIdLabel);
    		panel.add(liquorIdTextField);
    		panel.add(descLabel);
    		panel.add(descTextField);
    		panel.add(priceLabel);
    		panel.add(priceTextField);
    		panel.add(amountLabel);
    		panel.add(amountTextField);
    		
    		return panel;
    	}
    
    	private JPanel createButtonPanel() {
    		JButton addButton = new JButton ("Add"),
    				removeButton = new JButton ("Remove"),
    				updateButton = new JButton ("Update"),
    				saveButton = new JButton ("Save");
    		JPanel panel = new JPanel ();
    		panel.add(addButton);
    		panel.add(removeButton);
    		panel.add(updateButton);
    		panel.add(saveButton);
    	
    		return panel;
    	}
    }
    LiquorAppDemo.java
    Java Code:
    package liquorappdemo;
    
    import java.io.*;
    import java.util.*;
    
    public class LiquorAppDemo {
        public static void main(String... dataFile) throws IOException {
    	List<Liquor> liquors = new LinkedList<Liquor>();
    		
    	//1. Load the data from the text files, then test if it succeeded
            BufferedReader in = new BufferedReader(
    			new FileReader(new File(dataFile[0])) );
    	String line = "";
    	while((line = in.readLine())!= null) {
    		StringTokenizer st=new StringTokenizer(line);
    		while( st.hasMoreTokens() ) {
    		   int id=Integer.parseInt((st.nextToken()));
    		   String description=st.nextToken();
    		   double price=Double.parseDouble(st.nextToken());
    	           int amount=Integer.parseInt(st.nextToken());
                       Liquor myLiquor = new Liquor(id, description, price, amount);
                       liquors.add(myLiquor);
    		}
    	}
    	in.close();
            //1.a Now, test if it succeeded
    	for (Liquor l : liquors){
    		System.out.println(l);
    	}
    		
    		
            //2. Show the view
    	LiquorAppView gui = LiquorAppView.appear();
    	gui.refreshData(liquors);
    		
    	//3. Now you can work on it...
        }
    }
    And, of course, you need the text file in the format Taz_84 specified above

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Alright, if you're going to post some code, so will I, what the heck? It's not quite done yet, it's woefully lacking in comments, and I know absolutely that the original poster can't hand this in as his own, but nevertheless I had fun. Oh, it's set up for the text file to be with the java files and for the package to be dy08.m12.f.liquorApp, but obviously this can be easily changed.

    Edit: Oops, I forgot to add the "Liquor.java" class that was defined here, but this class must use that class as well.
    Attached Files Attached Files
    Last edited by Fubarable; 12-30-2008 at 02:19 PM.

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Exclamation

    Hm, I'm new to uploading here. Probably better to just upload a Jar file. While this is a Jar file, it's being renamed using a "zip" extension so it can be uploaded here.
    Attached Files Attached Files

  20. #20
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default Look above ^^^

    :-) Fubarable, you've done a perfect job. Well, this won't help Taz_84 to discover his original error, but... I compilded and run your program two minuts ago and I also read the source code. Well done! It's absolutly clear, a masterpiece of simplicity

    @Taz_84
    I think you should take the Fubarable jar and work on it. In your previous code it seems that you don't have a solid OOP & Java background. So I strongly suggest you to study the way Fubarable done your same task. His way is what is supposed to be done. Please note that
    • there are lots of classes (not just one big "monster" class like in your original project eh eh). This helps debugging, maintaing and reusing of code
    • the GUI logic is completely separate from the application login (MVC). This is a good philosophy, and can be simply followed with Java's swing package.
    • best plan leads to best code. Fubarable studied your problem BEFORE starting typing. You can see the result

    My strong advice is reimplementing your project starting on the Fubarable jar. Then study it and remeber his approach

    Luck

Similar Threads

  1. Replies: 3
    Last Post: 03-20-2009, 01:35 AM
  2. cannot be referenced from a static
    By Sidmyre in forum New To Java
    Replies: 2
    Last Post: 11-24-2008, 01:59 PM
  3. Replies: 11
    Last Post: 11-19-2008, 04:13 AM
  4. Replies: 1
    Last Post: 08-07-2007, 06:05 AM
  5. Replies: 1
    Last Post: 08-01-2007, 10:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •