Results 1 to 6 of 6
  1. #1
    keo
    keo is offline Member
    Join Date
    May 2010
    Posts
    34
    Rep Power
    0

    Default non-static variable cannot be referenced from a static context

    I tried googling, but still can't figure this out:

    I've got a GUI class and another class.

    I want to say when a radio button is selected in the gui class, it changes a variable.

    -variable-
    Java Code:
    private int variable = 0;
    -1 of the button method bodys-
    Java Code:
    ~~button header~~
    variable = 2;
    -getMethod-
    Java Code:
    public int getVariable() {
       return variable;
    }




    And in the other class:

    Java Code:
    public int getVariableHere(){
       int i = classGUI.getVariable();
       return i;
    }
    The Error appears on the line int i = classGUI.getVariable();

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

    Default

    Are you calling the getVariable method on the class or on an object of the class? You probably should be doing the latter.

  3. #3
    keo
    keo is offline Member
    Join Date
    May 2010
    Posts
    34
    Rep Power
    0

    Default

    getVariable() is getting this: private int variable = 0;

  4. #4
    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 keo View Post
    getVariable() is getting this: private int variable = 0;
    No, you don't understand. You are calling this method on this: classGUI

    and this appears to be a class, not an object of a class and that's not allowed. The solution is to create a classGUI object and call the method on that object.

  5. #5
    keo
    keo is offline Member
    Join Date
    May 2010
    Posts
    34
    Rep Power
    0

    Default

    THANK YOU! It has compiled now.

  6. #6
    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 keo View Post
    THANK YOU! It has compiled now.
    Good, I'm glad it compiles. Now you'll have to make sure that you are calling this method on the right object. Sometimes you don't want to create a new object for this, but rather have the correct object passed into your class so that you can act on it.

Similar Threads

  1. Replies: 7
    Last Post: 05-19-2010, 12:12 PM
  2. Replies: 3
    Last Post: 02-11-2010, 10:59 AM
  3. Replies: 3
    Last Post: 03-20-2009, 01:35 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
  •