Why am I getting a static reference error and how do I fix it?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SLDenman
    New Member
    • Sep 2010
    • 4

    #1

    Why am I getting a static reference error and how do I fix it?

    I am getting the "Cannot make a static reference to the non-static method add(Component) from the type Container" error on the last line where I am adding the Welcome label. Why and how do I fix it?

    Code:
    //import statements
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    //class header with extends JPanel
    public class LoanComparison extends JPanel
    {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	/**
    	 * 
    	 */
    	static JPanel mainPanel, centerPanel, bottomPanel;
    	static JLabel Welcome, loanAmount, years, rate, monthlypayment, totalpayment;
    	static JTextField loanTextField;
    
    	public static void main (String[]args)
    	{
    
    	//declare instance variables
    	int years, balance;
    	double loanAmount= 0, rate=0, monthlyrate=0, monthlypayment=0, totalpayment=0;
    	
    	//do following inside constructor method
    
    		//set inherited Panel to BorderLayout
    		//from here onwards, I will reference to this panel as main panel
    		mainPanel.setLayout (new BorderLayout());
    		JFrame frame= new JFrame("Comparing Loans");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		//set preferred size for the main panel
    		mainPanel.setLayout (new GridLayout (1,2,5,10));
    		
    		//create a label to display welcome message
    		//add the above label to the main panel
    		JLabel Welcome = new JLabel ("Welcome to Compairing Loans Application");
    		add (Welcome);
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    Looks like add() is a class method, therefore the class object must be referenced to access add()

    Comment

    • Dheeraj Joshi
      Recognized Expert Top Contributor
      • Jul 2009
      • 1129

      #3
      add is not a static method. So you need to access it using the object.

      Code:
      objname.method();
      Regards
      Dheeraj Joshi

      Comment

      • javabeginner1
        New Member
        • Dec 2011
        • 1

        #4
        Thanks

        thank u sorted my headache :))
        pweee..
        cheers very helpful

        Comment

        Working...