Non-static variable being used in static context

I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
However when i try to compare the string in the file with the one in the text field using the following code:
if ((line.compareTo(username)) == 0)
i get the following error...
"non-static variable being used in a static context"
Any ideas?

The static method doesn't know about instances of the class instead you pass the instance to the method:
static public void myMethod(MyClass instance, String var) {
  if(instance.line.compareTo(var))
And then the call would be:
MyClass.myMethod(anInstance, userName);

Similar Messages

  • Non-static variable cant accessed from the static context..your suggestion

    Once again stuck in my own thinking, As per my knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static context....'
    Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void main(String ar[]){      ////static context
    ������������ int counter=0; ///Non static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    �������������� System.out.println("Value of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    Jeff

    Once again stuck in my own thinking, As per my
    knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static
    context....'
    Now the thing is that, When we are declaring any
    variables(non-static) and trying to access it within
    the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void
    main(String ar[]){      ////static context
    ������������ int counter=0; ///Non
    static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    ��������������
    System.out.println("Value
    of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    w the question is that if we are trying to declare a
    variable out-side the method (Non-static) , Then we
    defenately face the error' Non-static varialble can't
    accessed from the static context', BUT here within
    the static context we declared the non-static
    variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    JeffHi,
    You are declaring a variable inside a static method,
    that means you are opening a static scope... i.e. static block internally...
    whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
    But if you put ... it will be considered as redundant by compiler.
    More over, static context does not get "this" pointer...
    that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller.

  • Static variable reference.

    I have written a small synchronized code
    class Foo implements Runnable {
    private byte[] myLock = new byte[0];
    public static void display(Foo f){
         synchronized(f.myLock){
         //Code to lock.
    }My question is:
    If I use synchronized(f.myLock),how can 'f' refer to a non-static variable
    myLock?
    Shouldnt static methods refer only to static variables?
    Am I missing a point?

    f is an instance of Foo, and f.myLock refers to the lock object of that very instance.
    If you just write myLock without specifying the object, it refers to the instance against which the current method is executing. But such an instance does not exist for a static method, so you can not use that "unadorned" myLock in a static method.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Static variable in openmp

    Hello all,
    I'd like to receive some hints about how to parallelize the code below that Thread Analyser has detected races for static variables:
    #pragma omp parallel for private(i)
    for (i=0; i<n; i++){
    x = calc(a);
    int calc(int a){
    static int x,y,z=0;
    x = 2 * a / 2.2345; // Thread Analyser detected write race here
    y = x * 3.4567; // Thread Analyser detected write race here
    z += x * y; // Thrd Analyser detected write and read races here
    return z;
    Best Regards,
    Glauber

    You can either declare the static variables as "threadprivate", or put the accesses to these variables in critical sections. Like
    int calc(int a){
    static int x,y,z=0;
    #pragma omp threadprivate(x,y,z)
    x = 2 * a / 2.2345;
    y = x * 3.4567;
    z += x * y;
    return z;
    or
    int calc(int a){
    static int x,y,z=0;
    int t;
    #pragma omp critical
    x = 2 * a / 2.2345;
    y = x * 3.4567;
    z += x * y;
    t = z;
    return t;
    Notice the use of 't' in the above code, as you cannot put a 'return' in a critical section.
    While the above techniques may get rid of the data races, they may not fix the problem you are facing. Making a code thread safe is more than merely getting rid of the data races. If you can show in more details how the static variables are used, we may be able to give more specific helps.
    -- Yuan

  • BPEL and Static variables

    Hi all,
    does anyone know how to define/use static variables inside a BPEL process? Or, is there any way so I can keep data from a (synchroneous) invocation to be used during the next (synchroneous) invocation?
    thanks for your help, I have been working on this for many many days !
    Abdel.

    How about a BPEL process that maintains your static variables and uses a custom correlation token. Queries to the process can retrieve the variable requested, and if they use the custom correlation token then the process will act as a singleton.
    I suggest using event processing rather than simple receive to handle the messages.

  • WCF static send port, use of custom behavior to change the endpoint location?

    The send port is outbound to various web service endpoints, all of which is the same WSDL just different location. Prefer to use the static port for features like ordered delivery. Is it possible to change the Microsoft.XLANGs.BaseTypes.Address dynamically
    by a custom behavior?
    https://ninithepug.wordpress.com/

    Hi,
    You can make static send ports partially dynamic, this can be achieved in a custom pipeline component in the send pipeline.
    You should refer to the below mentioned articles:
    Adding dynamic behavior to static send ports
    Using a Static Send Port like a Dynamic Send Port
    Rachit
    Please mark as answer or vote as helpful if my reply does

  • How a statics variable different from global variable...

    explain the span of these two kind of varaiables in subroutines..with a simple example
    Thanks guyz

    Check the following syntaxes to declare a static variable.
    1. STATICS f.
    2. STATICS f(len).
    3. STATICS: BEGIN OF rec,
    END OF rec.
    4. STATICS: BEGIN OF itab OCCURS n,
    END OF itab.
    Static validity means that, unlike normal local variables, the life of static variables does not depend on the defining procedure, but on the program at runtime. Static variables are thus not redefined on the stack each time the defining procedure is called, but exist independently of this in the program and keep their value, regardless of calls to the defining procedure.
    Global Variable:
    global variable is a variable that is accessible in every scope.

  • Non-static variable from a static context

    This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
    The error...
    Googler.java:27: non-static variable this cannot be referenced from a static context
              submitButton.addActionListener(new ButtonHandler());The code...
              JButton submitButton = new JButton("Submit Query");
              submitButton.addActionListener(new ButtonHandler());

    thanks for the response.
    I have already tried what you said but I tried it again anyway and i get the same error more less...
    Googler.java:28: non-static variable this cannot be referenced from a static context
              ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
    public class Googler
      static JTextField input1, input2;
         public static void main(String[] args)
              JFrame myFrame = new JFrame("Googler v1.0");
              Container c = myFrame.getContentPane();
              JLabel lab1 = new JLabel("Enter Google Query:");
              JLabel lab2 = new JLabel("Enter Unique API Key:");
              input1 = new JTextField(15);
              input2 = new JTextField(15);
              JRadioButton radSearch = new JRadioButton("Search Query");
              JRadioButton radCached = new JRadioButton("Cached Query");
              JButton submitButton = new JButton("Submit Query");
              ButtonHandler buttonHandler = new ButtonHandler();
              submitButton.addActionListener(buttonHandler);
              ButtonGroup group = new ButtonGroup();
              group.add(radSearch);
              group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
    Thanks
    Lee

  • Non-static variable from static context?

    Hi,
    I've created a program using swing components
    and I've set up a addActionListener to a button,
    button.addActionListener(this);
    when try and compile I get the following error:
    non-static variable this cannot be referenced from a
    static context
    button.addActionListener(this);
    I've checked site and my notes I don't seem to have
    done anything different from programs that have compiled
    in the past.
    I'm currently doing a programming course so I'm fairly
    new to Java, try not to get to advanced on me :)
    Thx in advance for any help.
    Chris

    Well what is declared static? If I remeber right this error means that you have a static method that is trying to access data it does not have access to. Static methods cannot access data that is intance data because they do not exist in the instance (not 100% sure about this but I believe it is true, at the very least I know they do not have access to any non-static data). Post some more of your code like where you declare this (like class def) and where you set up the button.

  • Non static  variable in static context

    import java.util.Scanner;
    public class project4_5 {
         int die1, die2;
         int comptotal = 0, playertotal = 0, turntotal = 0;
         int turn, comprun = 0;
         String playername;
         String action = ("R");
         Scanner scan = new Scanner(System.in);
            public static void main (String[] args)
            PairOfDice mydie = new PairOfDice();
         System.out.println("!!!!!!PIG!!!!!!");
         System.out.println();
         System.out.println("Enter your name! ");
         playername = scan.nextLine();
         while(playertotal>100 && comptotal>100){
         while(action.equalsIgnoreCase("R")){
                   System.out.println(playername+" roll or pass the die (R/P) ");
                   action = scan.nextLine();
                   if(action.equalsIgnoreCase("P"))
                        break;
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("You rolled a "+die1+" and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("You rolled a 1, you lose your points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("You rolled snake eyes, all points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   System.out.println("Would you like to roll or pass? (R/P)");
                           if(action.equalsIgnoreCase("P")){
                                playertotal = playertotal+turntotal;
                                turntotal = 0;
                   while(turntotal<=20||turns!=run){
                   turn = (int) (Math.random() * 5 + 1);
                   mydie.roll();
                   die1 = mydie.getFace1();
                   die2 = mydie.getFace2();
                   System.out.println("Computer rolled a "+die1+
                   " and a "+ die2);
                   if(die1==1||die2==1){
                        turntotal = 0;
                        System.out.println("Computer rolled a 1 he loses hi points"
                        +" for this turn.");
                        break;
                   else if(die1==1&&die2=1){
                        playertotal = 0;
                        System.out.println("Computer rolled snake eyes, his points have"
                        + " been lost.");
                        break;
                   else
                   turntotal= turntotal+die1+die2;
                   comprun++;
                   turntotal = 0;
       }here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
    if u need it my die class is below
    public class PairOfDice
         int faceValue1, faceValue2;
         public PairOfDice()
              faceValue1 = 1;
              faceValue2 = 1;
         public void roll()
              faceValue1 = (int) (Math.random() * 6 + 1);
              faceValue2 = (int) (Math.random() * 6 + 1);
         public int getFace1 ()
              return faceValue1;
         public int getFace2 ()
              return faceValue2;
         

    It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
    You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
    If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
    public static void main(String[] argv) {
        project4_5 game = new project4_5();
        game.play();
    }Then create a method called play:
    public void play() {
      // put everything that's currently in main() in here
    }See if that fixes it for you.

  • Non-static variable total cannot be referenced from a static context

    i am trying to write a program that uses the if-else statements and when i wrote my program i got "non-static variable total cannot be referenced from a static context" for three lines of my input.
    A:\Disks.java:20: non-static variable total cannot be referenced from a static context total = (10000 * .95 + ((diskCount - 10000) * .85));
    ^
    A:\Disks.java:22: non-static variable total cannot be referenced from a static context total = (diskCount * .95);
    ^
    A:\Disks.java:24: non-static variable total cannot be referenced from a static context System.out.print(total);
    ^
    Do you know what I did wrong?

    I apologise in advance for the general tone of this reply.....
    Ummm, let me think for a second... You referenced a non static
    variable from a static context. Yup, yup. That's it !
    If you can't figure this out, you really need to do a Java tutorial or
    buy a text book. Basically though, total is a member of some class
    and you are trying to use it from a static function. I bet you have
    something like:
    public class Test {
        public int total;
        // blah blah blah
        public static void main(String[] args) {
            // This won't work cos "total" is a member and we are static
            System.out.println(total);
            // This works cos now you have an instance to pull total
            // out of.
            Test t = new Total();
            System.out.println(t.total);
    }

  • Non-static variable aceYears cannot be referenced from a static context

    This is my error...
    investment.java:53: non-static variable aceYears cannot be referenced from a static context
    lwInvest.numberAceYears(aceYears);
    ^
    This is my code...
    public static void main (String[] args)
    investment.Invest.numberAceYears(aceYears);
    and more code
    String termInvested = JOptionPane.showInputDialog
    ("Please enter the amount of years to invest your investment.");
    int intTermInvested = Integer.parseInt(termInvested);
    and yet more code..
    public void numberAceYears (int aceYears)
    for (int aY = 5 ; aY <= aceYears; aY++)
    double aceInterest = aceCoBalance * aceCoRate /100;
    aceCoBalance = aceCoBalance + aceInterest;
    aceYears = aceYears + aY;
    Suggestions?

    Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
    For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
    http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

Maybe you are looking for

  • Tennis Channel and Customer Service

    My saga continues.  Let me first start out by saying that I divorced DIRECTV to come to Verizon.  So far with the exception of your customer service,  the marriage has been great.  I was watching the Tennis Channel last on Sunday; the Mutua Madrid Op

  • Error in the Standard MSS iview?

    Hi, I am using "startprocess" mss iview from Content Provided By Sap,when click on preview it shows bellow error.But same iview is working in my Development System. Error com.sapportals.portal.prt.runtime.PortalRuntimeException: Failed in WD JNDI loo

  • Transferring photos from MacBook Pro to a SD Card

    Hello, New chap on the block and a complete ignoramus! I have just moved from a windows 7 based laptop to Macbook Pro with OSxLion. I am slowly learning, howevr I have two problems that I cannot seem to resolve. 1: I put my 2gb brand new SD Card in t

  • Clear CMOS Problem

    I have the Neo 2 Plat I cleared the cmos the way the directions said by moving the jumper to slots 2-3 when the comp was off. Then I moved the jumper to 1-2 turned the comp back on and got the following error. CMOS Checksum error-defaults loaded

  • NEW SLAVE HD NOT FOUND

    I recently installed a second hard drive as a slave. All the installation process went fine, I put some of my personal files in the new slave, but I was trying to change the settings in my slave so that I could be the only one with access to those fi