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

Similar Messages

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • 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 addressed to Static Variable

    Hi,
    I am new to java, I am getting (Non Static Variable sb,serverAddress addressed to Static Variable)
    Here is the code. Thanks for reading, any help or explanation would be appreciated-
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package webcheck;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    * @author
    public class checkhttp {
          private URL serverAddress = null;
          private StringBuilder sb = null;
          public checkhttp(java.net.URL serverAddress,java.lang.StringBuilder StringBuilder)
              this.serverAddress=serverAddress;
              this.sb=sb;
      public static void main(String[] args) {
          HttpURLConnection connection = null;
          OutputStreamWriter wr = null;
          BufferedReader rd  = null;
          String line = null;
          int x;
          //checkhttp check= new checkhttp();
          try {
              serverAddress = new URL("http://www.yahoo.com");
              //set up out communications stuff
              connection = null;
              //Set up the initial connection
              connection = (HttpURLConnection)serverAddress.openConnection();
              connection.setRequestMethod("GET");
              connection.setDoOutput(true);
              connection.setReadTimeout(10000);
              connection.connect();
              //get the output stream writer and write the output to the server
              //wr = new OutputStreamWriter(connection.getOutputStream());
              //wr.write("");
              //wr.flush();
              //read the result from the server
              rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              sb = new StringBuilder();
              while ((line = rd.readLine()) != null)
                  sb.append(line + '\n');
              System.out.println(sb.toString());
              System.out.println("Server is up");
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (ProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          finally
              //close the connection, set all objects to null
              connection.disconnect();
              //rd = null;
              //sb = null;
              //wr = null;
              connection = null;
    }

    Someone please correct me if I'm wrong, but since main is static, any fields it access must also be static.
    The static keyword declares that something is accessable no matter the class state, thus you can call main() and run your program without having something make an instance of the object that your progam defines. For example:
    class Foo {
          static public String strText = "Hello World";
    //Later in some method, this is valid.
    String MyString = Foo.strText;
    //However, if strText was not static you need to
    Foo fooExample = new Foo();
    String myString = fooExample.strText;Static should not override private, so static private fields/members are not accessable. To be accessable you still need to be public.
    Edited by: porpoisepower on Jan 21, 2010 2:18 PM

  • How to access static variable from a Thread class

    Kindly help me.......
    here's the code.....
    class Thread1 extends Thread
    int j=0;
    myClass2 mc = new myClass2();
         public void run()
              for( int a=0;a<6;a++)
                        {try
                             { Thread.sleep(5000);
                             catch(Exception e){System.out.println("Interrupted Exception");}
                             j++;
    mc.change1(i);
    } System.out.println("Thread1 executes "+j+" times");
    class Thread2 extends Thread
    int k=0;
         myClass2 mc1 = new myClass2();
         public void run()
              for( int a=0;a<6;a++)
                        {try
                             { Thread.sleep(5000);
                             catch(Exception e){System.out.println("Interrupted Exception");}
                             k++;
    mc1.change2(i);
    }System.out.println("Thread2 executes "+k+" times");
    class myClass2
    static int i=5;
    public synchronized void change1(int s)
    s=6;
    System.out.println("New value of i:"+s);
    public synchronized void change2(int s)
    s=7;
    System.out.println("New value of i:"+s);
         public static void main(String args[])
    Thread1 b1 = new Thread1();
    Thread2 b2 = new Thread2();
         b1.start();
    b2.start();
    I am unable to pass the variable i in my method call in Thread1: mc.change1(i); and similarly in Thread2:mc.change2(i);

    You can declare your i variable in myClass2 as public static and then simply call there
        mc.change1( myClass2.i ) ;

  • How to invoke a non-static member from a static reference?

    Hello JDC
    My program consist of several classes. I find it more readable,logic and useful to declare all the methods in all the classes �static� and get access by Class.member().
    The problem showed up when I must use a java biuld-in method( as Component.remove ) within my static method , then I receive compile error.
    The first alternative is to create the class instance inside the static my static method , the second is to use interface which declare its member as static final. The two ways doesn�t fit to my needs , do anyone know another way?
    Thanks in advance
    Shay

    Hi
    im sorry but im not sure what you mean by "OO desgin". i'll appreciate if you'll link me some sources about this , its sound very interesting .
    It may be that you are moving to Java from COBOL or >FOTRAN or something and you are not comfortable with >OO philosophy
    For example, you can never have two instances of >the same class have different properties. What's the >point of having classes at all if you are going to do it >this way? Java is my first language , you sound very unhappy about the way i ignore the OOP , i think you right in some terms but i need to exam my thinking again and think how can i implements the same ideas in a form of OOP. whenever all those information will come i'll be able to response.
    thanks for your reply
    Shay Gaghe

  • Accessing static variable from subclass

    Hi,
    this question is probably fairly common but I can't seem to find the answer around: Can somebody please explain the rationale behind the following behavior ?
    public abstract class SuperClass {
        static String mess;
    public class SubClass extends SuperClass {
        static {
            mess = "Hello world!";
        static String getMess() {
            return mess;
    public class mymain {
        public static final void main(String[] args) {
            System.out.println(SubClass.getMess());
    }gives "Hello world!" as expected whereas
    public abstract class SuperClass {
        static String mess;
        static String getMess() {
            return mess;
    public class SubClass extends SuperClass {
        static {
            mess = "Hello world!";
    public class mymain {
        public static final void main(String[] args) {
            System.out.println(SubClass.getMess());
    }gives "null". It looks like the initialization block is not executed. Why?
    Thanks for your insight,
    Chris

    >
    You're essentially claiming you need to override some static methods.No, there is indeed misunderstanding here. What I need to do is implement the methods with the signature given, I'm not overriding existing methods, in fact I'm not even deriving from any existing class. I only have to create the entry points in my code as defined, then publish them to the DB, and Oracle is going to use them (I think they can be called callbacks, also again not 100% sure).
    Then it happens that in my particular case it's natural to have a master containing all the code and then subclasses that only define a few specific parameters that are to be used by the static (and instance) methods. Hence the final design. Currently my code looks like the following and seems to work (fingers crossed):
    class ParseFileCLL extends ParseFile {
        // Name of the row type.
        private final static String rowType = "CLLROW";
        // Here I initialize static fields of the ParseFile master class.
        static {
            fileType = "CLL";
            fileStruct = new FileStruct(34);
        // Type methods implementing ODCITable interface.
        static public BigDecimal ODCITablePrepare(STRUCT[] sctx, STRUCT tfinfo, String sysName)
                throws SQLException {
            // prepareContext is a static helper method defined in the master class.
            return prepareContext(funcType, rowType, rowSetType, tfinfo);
    // Other ODCI methods are only accessed directly in the master class, NOT in the subclass. Or else... WEIRD BUGS!
    // In other words:
    //  publish ParseFile.ODCITableStart() -> ok
    //  publish ParseFileCLL.ODCITableStart() -> crash
    }Not surprising. Java has plenty of undefined or inconsistently-defined behavior. The JLS is by no means perfect.
    >
    Well I kind of admire your composure about this, but it seems to me that if it's indeed the case, the meaning of it would be that the code could work in JVM 1.5.0.15 and not in 1.5.0.16, or worse run ok on Windows and not on Linux, which is if I understand correctly precisely the kind of behavior that Java was meant to cure, at least at its inception.
    I think there might be other elements to the story though.
    Thanks,
    Chris

  • VM NIC keeps changing from Dynamic to Static IP (from a static IP pool)

    Back ground:
    Having migrated our VM's from 2008R2 and 2012SP1 servers into one 4 node 2012R2 Hyper V Cluster we have a problem with NIC's being changed to Static IP, this in turn gives a range of warning and errors when
    moving VM's between the nodes (example during a live migrate or when we put a node in maintenance mode). 
    The cluster share a Logical Switch, this switch has 1 Uplink. The uplink is a Port Profile called "TrunkPort" and it contains lots of network sites. Each network site links to a Logical Network, each Logical Network is basically a VLAN on our Cisco
    router/switch.
    We don't have any IP Pools configured since we assign all VM's a static IP manually or they use DHCP provided by our AD servers.
    When we change a NIC to from Static IP to Dynamic (there might be power shell to do this), bit in the GUI its painfull as you have to shutdown the VM remove the adapter and create a new one. I does not last long as the system after a few minutes changes
    the NIC configuration back to Static IP again. Any idea why and how to stop it?
    example of errors after a migration that completed w/ Info :
    Error (23801)
    No available connection to selected VM Network can be found.
    Recommended Action
    Ensure host NICs have connection to the fabric network on which VM Network is created.
    Error (23810)
    There is no host NIC with required classification.
    Recommended Action
    Ensure that there NICs with required classification on a host.
    Error (23806)
    All available ports on switch extension  has been used.
    Recommended Action
    Ensure there are free ports available on a switch extension.
    Error (23808)
    All available ports on port profile  has been used.
    Recommended Action
    Ensure that there are free ports available on a port profile.
    Error (23807)
    The switch extension  has reached maximum supported ports on this host.
    Recommended Action
    Ensure there are free ports available on a switch extension per host.
    Error (23809)
    The port profile  has reached maximum supported ports on this host.
    Recommended Action
    Ensure that there are free ports available on a port profile per host.
    Error (23825)
    The virtual machine requires a logical switch connection and the host network adapter is not attached to a logical switch or operating system doesn't support logical switch.
    Recommended Action
    Ensure operating system supports logical switch and there is a logical switch connection for the host or remove the network interface card from the virtual machine and try the operation again.
    Error (23753)
    The virtual machine or tier load balancer configuration requires an IP pool and there are no appropriate IP pools accessible from the host.
    Recommended Action
    Select a host with access to an appropriate IP pool and try the operation again.
    Warning (23830)
    Unable to find compliant logical switch.
    Recommended Action
    Fix logical switch compliance state.
    Note: a server configured with Dynamic NIC will move between nodes without any errors (nice green tick box icon), our problem is that SCVMM or the servers deside to reconfigure the NIC's to Static IP when ever they see fit!!

    I feel like some issue with the Fabric configuration.
    If you are create a new VM through SCVMM, do you face this issue? (While creating the new VM, on the hardware configuration page, use dynamic IP and Dynamic MAC)
    The first event which you listed says about missing VM Network.
    No available connection to selected VM Network can be found.
    Please check the VM Network to where the VM is connected through SCVMM. And check if all the nodes have the same VM Network.
    If thats missing, fixing it might fix few other errors which you mentioned.
    Optimism is the faith that leads to achievement. Nothing can be done without hope and confidence.
    InsideVirtualization.com

  • 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);
    }

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • Changing static variable

    hi all,
    i am in the process of developing a robotic controlling software using rxtx and java.
    in that software ther will be 16 static integer value in a class.
    in gui 16 text field will be ther and a button lebeled "send data",
    my problem is that how to change static variable from the action event of a jbutton???
    expecting some suggestion
    arnab/vu2bpw

    * Test1.java
    * Created on January 11, 2007, 5:13 PM
    * To change this template, choose Tools | Template
    Manager
    * and open the template in the editor.
    package ab;
    * @author Arnab
    class StaticTest{
    ublic static int p=5;
    public static int q=6;
    static void boom()
    System.out.println("hello from static boom");
    System.out.println(p);
    public static int getP() {
    return p;
    public class Test1 {
    /** Creates a new instance of Test1 */
    private static int r=10;
    int b=15;
    public static void main(String args[])
    System.out.print("hellow world");
    //change_static();
    StaticTest test1 = new StaticTest();
    r=test1.getP();
    StaticTest.p=b; //####error:-non static variable b
    cannot be refereanced
    from a
    static context
    static void change_static(int a)
    this is the test code of my problem.
    netbeans generating this errorYour code is confusing. You declare a variable as StaticTest, and instantiate it, but you call it test1, which is also the name of the class with main in it. However, your problem is exactly what the compiler is telling you, the non-static variable b cannot be referenced from the static context main(). Either intantiate an instance of Test1 class, or make b static.
    public class Test1{
    private static int r = 10;
    int b = 15;
    public static void main(String [] args){
        Test1 test1 = new Test1();
        r = StaticTest.getP();
        StaticTest.p = test1.b;
        System.out.println("StaticTest.p = " + StaticTest.p + " -- Test1.r = " + r);
    }~Tim

Maybe you are looking for

  • Error while validating application in version 11.1.2.2

    Hi guys, This is the first time I work with EPMA, and I find it really challenging! 1) While trying to deploy the application after updating the Shared Library (all dimensions in the application are shared), I got the following error: "Error: The 'Vi

  • Colors shift when a PDF file contains transparent image

    Hello, I tried to programatically set a soft mask to an image by using the Addobe PDF Library, in order to make part of the image transparent. The image color space is RGB. I used PDEImageSetSMask() funtcion for setting the mask. I also have a PDF fi

  • New PDF portfolios without the old options

    Previously, we created PDF portfolios so users can view all 3 PDFs in one document. Now, with the latest version of Adobe, the PDF portfolio templates and options are all different. Users must extract each PDF (within the portfolio) to be able to vie

  • Sim not vaild

    hello i recently bought an iphone5c from sprint and cant get it to start from a differnt carrier what is going on

  • Consuming a Liferay portlet from WebCenter

    Hi all, I'm trying to consume the default Liferay "Hello World" portlet from WebCenter but keep on getting a null portlet instance when trying to drop the portlet on a jspx page. Any help would be greatly appreciated. Regards Antonis