HELP: Cannot refer to non-final variable inside inner class

Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
Can anyone offer any advice how to fix this?
static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
     boolean bDone = false;
     Element e;
     SAXReader sax          = new SAXReader();
     FileInputStream fis     = new FileInputStream( args.getInputFile() );
     Document document     = sax.read( fis );
     Element root = document.getRootElement();
     if( root.getName().equals( "Sheet" ) )
          XMLParser.iterateElements( root,     new XMLElementCallback()
                                                  public void onElement( Element element )
                                                       XMLParser.iterateAttributes( element,     new XMLAttributeCallback()
                                                                                               public void onAttribute( Element element, Attribute attribute )
                                                                                                    if( attribute.getName().equals( "guid" ) )
                                                                                                         e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
                                                                                                         // WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
                                                                                                         for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
                                                                                                              Attribute a = (Attribute)it.next();
                                                                                                              if( a.getName().equals( "randOffset" ) )
                                                                                                                   Integer i = new Integer( resolver.getTotalPermutations() );
                                                                                                                   a.setValue( i.toString() );
                                                                                                                   bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
          if( ( !bDone ) && ( e != null ) )
               Integer i = new Integer( resolver.getTotalPermutations() );
               e.addAttribute( "randOffset", i.toString() );                                                                                                                                            
     FileOutputStream fileOut     = new FileOutputStream( args.getInputFile() );          
     OutputFormat format               = OutputFormat.createPrettyPrint();          
        XMLWriter xmlWriter               = new XMLWriter( fileOut, format );
        xmlWriter.write( document );
        fileOut.close();
}PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
Thanks in advance.

It is already set to that - it does look correct in Eclipse, honest.
It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Non-final variable inside an inner class - my nemisis

    I have an issue with accessing variables from an inner method. This structure seems to allow access to the text objects but not to the button object. This comes from a bit of example code that just illustrates a simple form window with text fields and buttons that read them.
    At the start of the class I have text objects defined like this:
    public class SimpleGUI extends Composite {
    Text nameField;
    Text junkField;
    // Constructors come next, etc...
    Later within this class there is a method to create some GUI stuff, and then to create a button and when pressed access and print the text to the console
    protected void createGui(){
    junkField = new Text(entryGroup,SWT.SINGLE); //Ross
    junkField.setText("Howdy");
    Button OKbutton = new Button(buttons,SWT.NONE);
    OKbutton.setText("Ok");
    OKbutton.addSelectionListener(
    new MySelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
    System.out.println("Name: " + nameField.getText());
    System.out.println("Junk: " + junkField.getText());
    And that all works fine. So within the inner class, the object junkField can be accessed nicely.
    However if I try to do the same with the button (I want to change the label on the button after it's pressed) I get errors for trying to access a non-final object in an inner class.
    I tried to handle the button similar to the text, adding this after the text defs:
         Button myButton;
    and under the println's in the inner class I wanted:
    if OKbutton.getText.equals("OK") {  OKbutton.setText("NotOK")}
    That's when I get an issue with "cannot refer to a non-final variable inside an inside class defined in a different method"
    Now, if I move the button declaration into the createGui method, and declare it with "final Button myButton" it works.
    Why does the button need different treatment than the text?
    Is this a suitable method to make my button change it's label when pressed, or is this sloppy?

    Button is a local variable. The anonymous inner class object you create can continue to exist after the method ends, but the local variables will not. Therefore, as the error message says, you must make that local button variable final if you want to refer to it inside the anon inner class. If it's final, a copy of its value can be given to the inner class--there's no need to treat it as "variable."

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • Problem with final variables and inner classes

    variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
    Is there any solution to this?
    Exception is:
    java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
         at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
         at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
         at java.awt.Component.processMouseEvent(Component.java:5131)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

  • Error message: "Attempt to use a non-final variable..."

    I get the following error message
    "....java:771: Attempt to use a non-final variable rightColumn from a different method. From enclosing blocks, only final local variables are available.
              switchToOrderform4( backArrow_J, fwdArrow_J, rightColumn, c, jobticketEnclosure ); // ------- the problem line"
              ^
    The variable is "rightColumn."
    I instantiate it in one class, "Class1."
    Pass it as a parameter to second class, "Class2."
    Pass it as a parameter to a third class, "Class3."
    Pass it as a parameter to a method, "method1( ... )."
    -- Declared & instantiated here, passed as a parameter to
    class Class1 extends JPanel {
         private JLabel rightColumn;
    class Class2 extends MouseAdapter {
    JLabel rightColumn,
    --Passed as a method paramter, causing the compiler error (line 771):
    class Class3 extends JPanel {
    Line 75:      JLabel rightColumn;
    Line 165:                          JLabel rightColumn,
    Line 255:      this.rightColumn = rightColumn;
    Line 771:           method1( backArrow_J, fwdArrow_J, rightColumn, c, jobticketEnclosure ); // ------- the problem line
    Declaring the variables final does not help. How do I fix this?
    Many thanks in advance.

    Hmm that's a puzzler. I would love to see a complete (but minimal) example of this.
    You might get more insight by using a different compiler, since you'd get a different version of the error message. Some compilers are more lucid than others.

  • Why we are making a variable as final in method inner class ?

    Why we are making the variable as final (method inner class) while we are accessing the method variable in inner class ?
    regards,
    namanc

    As far as I can tell, the only reason is to protect the programmer: when the inner class instance is constructed, it is given the then-current value of the variable. If the variable (or method parameter) later changes, the value held by the inner class would not. By making the variable final, the programmer doesn't have to worry about them staying in sync.
    Here's some code to ponder:
    public class InnerExample
        void printMe( final int x )
            Runnable runMe = new Runnable()
                public void run()
                    System.out.println(x);
            (new Thread(runMe)).start();
    }When compiled with the Sun JDK 1.4.2, you get this bytecode:
    void printMe(int);
      Code:
       0:   new     #2; //class InnerExample$1
       3:   dup
       4:   aload_0
       5:   iload_1
       6:   invokespecial   #3; //Method InnerExample$1."<init>":(LInnerExample;I)V
       9:   astore_2
       10:  new     #4; //class Thread
       13:  dup
       14:  aload_2
       15:  invokespecial   #5; //Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
       18:  invokevirtual   #6; //Method java/lang/Thread.start:()V
       21:  returnAt line (byte) 5, it loads the passed value onto the stack; at line 6, it invokes the inner class constructor (which is created by the compiler). Nothing in this sequence of code would prevent use of a non-final variable.

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Synchronize on objects held in non-final variables?

    [This thread|http://forums.sun.com/thread.jspa?messageID=10775877#10775877] and post got me thinking:
    linuxisbest.eric wrote:
    I have noticed in my textbook that it creates a String in two ways:
    String a = new String("Hello");and
    String a = "Hello";Which one should I use? Is there any practical difference?
    YoungWinston wrote:Pick door number two linux ... unless you plan on synchronizing on it, that is.
    WinstonIs it best practice to only synchronize on objects held in final variables?
    Edited by: Encephalopathic on Jul 26, 2009 5:46 AM

    gnat wrote:
    Is it best practice to only synchronize on objects held in final variables?
    Above [best practices|http://en.wikipedia.org/wiki/Best_practices] apply to cases when lock is not intended to change.
    I think that there could be cases when lock is actually intended to change and therefore shouldn't be final. Here's an example of caching code I've seen recently:
    private final ConcurrentMap<Integer, Object> pendings
    = new ConcurrentHashMap<Integer, Object>();
    public Object loadEntity(int entityId) {
    Object lock = new Object(); // shouldn't be final, see below
    Object prev = pendings.putIfAbsent(entityId, lock);
    if(prev != null) {
    // without using prev lock, there would be a chance
    //  for concurrent threads to perform redundant invocation
    //  of retrieveEntityFromSomewhereSlowly for same entityId
    lock = prev;
    Object res;
    synchronized (lock) {
    res = getEntityFromCacheQuickly(entityId);
    if (res == null) {
    // cache miss - retrieve entity slowly:
    res = retrieveEntityFromSomewhereSlowly(entityId);
    pendings.remove(entityId);
    gnat,
    Huh? Please could you try to talk me through that code... At first glance, I don't follow it... I think it's still got "unprotected race conditions", but after reading it through several times (in the course of trying to frame a post saying basically "I don't think that will work, and here's why" I now think I understand how it does work (almost all the time), but I'd just really really like some validation of my mis/understanding.
    So... Here's how I think that works... please could you verify or repudiate my understanding.
    package forums;
    import java.util.Random;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.ConcurrentHashMap;
    class GnatsThreadsafeCache
      private static final Random random = new Random();
      // pending locks := entityId --> lock
      private final ConcurrentMap<Integer, Object> pendingLocks = new ConcurrentHashMap<Integer, Object>();
      // cache := entityId --> entity
      //          1        --> "1"
      private final Map<Integer, Object> cache = new HashMap<Integer, Object>();
      public Object loadEntity(int entityId) {
        Object lock = new Object(); // shouldn't be final, see below
        // putIfAbsent: If the specified key is not already associated with a value,
        //  associate it with the given value. Returns the previous value associated
        //  with the specified key, or null if there was no mapping for the key.
        Object previousLock = pendingLocks.putIfAbsent(entityId, lock);
        if(previousLock != null) {
          // without using previousLock lock, there would be a chance
          //  for concurrent threads to perform redundant invocation
          //  of retrieveEntityFromSomewhereSlowly for same entityId
          lock = previousLock;
        Object entity;
        synchronized (lock) {
          entity = getEntityFromCacheQuickly(entityId);
          if (entity == null) {
            // cache miss - retrieve entity slowly:
            entity = retrieveEntityFromSomewhereSlowly(entityId);
            addEntityToCache(entityId, entity);
        pendingLocks.remove(entityId);
        return entity;
      private Object getEntityFromCacheQuickly(int entityId) {
        DEBUG("> getEntityFromCacheQuickly("+entityId+")");
        Object entity = cache.get(entityId);
        DEBUG("< getEntityFromCacheQuickly returns "+entity);
        return entity;
      private Object retrieveEntityFromSomewhereSlowly(int entityId) {
        DEBUG("> retrieveEntityFromSomewhereSlowly("+entityId+")");
        try{Thread.sleep(random.nextInt(1000));}catch(InterruptedException e){System.err.println(e);}
        Object entity = Integer.toString(entityId);
        DEBUG("< retrieveEntityFromSomewhereSlowly returns "+entity);
        return entity;
      private void addEntityToCache(int entityId, Object entity) {
        DEBUG("| addEntityToCache("+entityId+", "+entity+")");
        cache.put(entityId, entity);
      public static void main(String[] args)
        final GnatsThreadsafeCache cache = new GnatsThreadsafeCache();
        for (int i=0; i<10; i++) {
          new Thread(
            new Runnable() {
              @Override
              public void run() {
                int i = random.nextInt(4);
                Object entity = cache.loadEntity(i);
                DEBUG("~ "+i+"-->"+entity);
          , "Thread"+i).start();
      private static void DEBUG(String message) {
        System.err.println(Thread.currentThread().getName()+": "+message);
    }How it works:
    1. create a new lock object.
    2. check if entityId exists in the previousLock list... that's a ConcurrentMap so the putIfAbsent operation is atomic (i.e. syncronised on the previousLock object).
        ~  This operation is "garanteed fast"; ergo it involves no heavy "business object" creation/retrieval.
    3. Now, if the entityId already exists in the previousLock list we syncronize on it, allowing one-thread-at-a-time to traverse "the crytical block" where we check if the-entity associated with the-given-entityId is allready cached, and retrieve it, otherwise create a new one (which will take an arbitrary "long time").
    So what? Well I think it means that we've reduced contention to the individual entity level, as apposed to the "collection level"; as you would get if you just used a "standard" ConcurrentMap as the cache... which means that we've (probably) increased the throughput because each thread is blocked only upon those other threads which definately would stuff-them-up (waiting for the heavy "business object" creation routine to complete); as apposed to those that just might stuff them up (but won't because they're actually retrieving different entities).
    In short: It's a way of blocking on distinct keys?
    Is that correct?
    Thanx in advance for your thoughts.
    Cheers. Keith.
    Edited by: corlettk on 1/08/2009 11:05 ~~ Removed extranious cache.get from retrieveEntityFromSomewhereSlowly.

  • Setting variables from inner class

    I have a GUI that takes users information and provides a quotation as componants are clicked. My componants' Listeners are in seperate inner classes and from these I want to add certain details to variables, it seems to compile and run but it doesn't seem to be changing the value of the variable when the componants are clicked, is there any reason why this happens, my code is below:
    public class MyGUI extends JFrame{
            public MyGUI(){
              //GUI STUFF HERE
            double Price;
         private String total=calculate();
         public String calculate(){
              double aTotal=Price;
              return "$ " + aTotal;
         class MyListener implements ItemListener{
              public void itemStateChanged(ItemEvent evt){
                   if(evt.getSource()==rad1) {
                   Price=0.10;
                   else if(evt.getSource()==rad2) {
                   Price=0.12;
                        totalLab.setText(total);
    }

    shouldn't I also be able to access the outer classes methods? It doesn't seem to do this either.

  • Final variables

    Hello All
    I have a question and this contradicts what I have learned so I will like to have a good explanation for this.
    public class Foo {
    private final int x = 5;
    private byte b = x;
    will this compile? The answer is YES it will compile. Now if you take out the final keyword from int x will it compile? The answer is NO it will not.
    Why is this???????
    Thanks in Advance for your help!!!!

    sorry, but my compiler (jdk1.3) compiles the code :
    public class test
    private int x = 5;
    private int b = x;
    There is one thing you are missing is that it is instead of int b it should be byte b, now let see if you can make the above code compile under the jdk1.3 compiler. Now change the private int x to private final int x and compile your code...
    I think the compiler inserts an implicit (invisible)
    constructor that is called before any other explicitly
    defined constructor. And this implicit constructor
    makes the assignments, and thus you can use any
    non-static and non-final expression for
    initialization. Even this :
    class a
    int x;
    class b
    int y = x;
    And this really makes sense !!!
    When class a instanciates class b (if there was an
    explicit constructor), the implicit constructor first
    assigns x to y and after that the explicit constructor
    is called.
    also think of that :
    public class test
    int x;
    int y = x;
    this also compiles, because all variables are always
    (implicitly) initialized with 0 (and corresponds like
    false and null).
    enough ?I think you are right the compiler might insert an implicit(invisible) constructor, but the above explanation still doesn't explain why it treats final variable differently then non-final variables??? Thanks for replying!!!!

  • Final in inner class

    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?
    Thanks!
    int SIZE = 1; //somewhere else
            for( int size = 0 ; size < 5 ; size++){
                  Circle circle = new Circle(D/Padding);
                  circle.setOnMousePressed(new EventHandler<MouseEvent>(){
                      public void handle(MouseEvent me){
                          SIZE = size;
             );edit:
    I am well aware this isnt neccesarily a javafx specific thing, but more of a general java poor programming knowledge.
    I also know that the mouseadapter is an anonymous class and can only access final.
    I am just looking for any suggestions on how to best handle this.
    Edited by: namrog on Jul 5, 2011 10:51 AM
    Edited by: namrog on Jul 5, 2011 10:59 AM

    namrog wrote:
    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.Yes, that's the point. If a local variable is to be used by an instance of a nested class, that nested instance can live on long after the local variable goes out of scope. So it needs its own, separate copy of the variable. However, since, as far as we are concerned, there is only one variable, that variable needs to be final, so that there will not be issues with keeping the two copies' values coherent.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?Create a final variable and copy the value of your non-final variable to it.
    int nonFinal =...;
    final int theFinalCopy = nonFinal;
    new Whatever() {
        void doStuff() {
          doSomething(theFinalCopy);
    }

  • Help me please~ non-static variable rs cannot be referenced ...

    i make counter
    but this error occurrence
    only i doing resultset make and closed
    why non-static variable rs ....
    i am sorry i don't speak English ...
    help me please..
    error message
    non-static variable rs cannot be referenced from a static context
    source
    ===============================================
    package jjaekim;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Count{
              Statement stmt;
              ResultSet rs;
              ResultSet rs2;
              Connection conn;
              //DBPoolManager dbpm;
         public static String add(HttpServletRequest request){
              try{
                        int year =0;
                        int month=0;
                        int date =0;
                        int hour =0;
                        int min     =0;
                        int week =0;
                        String str_date=new String();
                        String str_time=new String();
                        String referer_url     =request.getHeader("Referer");
                        String infomation     =request.getHeader("User-Agent");
                        String ip               =request.getRemoteAddr();
                        int access_date=0;
                        int access_time=0;
                        Calendar cal     =Calendar.getInstance();
                        year               =cal.get(cal.YEAR);
                        month               =cal.get(cal.MONTH) + 1;
                        date               =cal.get(cal.DATE);
                        hour               =cal.get(cal.HOUR_OF_DAY);
                        min                    =cal.get(cal.MINUTE);
                        week               =cal.get(cal.DAY_OF_WEEK);
                        access_date          =(month*100)+date;
                        access_time          =(hour*100)+min;
                        if(access_date<1000)
                             str_date="0"+new Integer(access_date).toString();
                        else
                             str_date=new Integer(access_date).toString();
                        if(access_time<100)
                             str_time="0"+new Integer(access_time).toString();
                        else
                             str_time="0"+new Integer(access_time).toString();
                   }catch(Exception e){
                        //System.out.print("Exc"+e.getMessage());
                        //return false;
                   finally{
                             if(rs!=null){
                                  try{     rs.close();}catch(Exception e){}
                             if(rs2!=null){
                                  try{     rs2.close();}catch(Exception e){}
                             if (stmt!=null){
                                  try{     stmt.close();}catch(Exception e){}
                             //if (conn!=null){
                                  try{     conn.close(); }catch(Exception e){}
                        //return back;
    /*     public static void main(String[] args)
              System.out.println("Hello World!");

    Hello jjaekim,
    if rs is a class variable (the same value for all objects),
    try this (more likely to be the right solution) :
    static ResultSet rs;
    instead of :
    ResultSet rs;
    if rs has a different values in different objects,
    then you should add the object name when using it like this :
    myObject.rs or this.rs

  • Non-static variable Help needed

    Hi, I am creating a multi threaded web server but get the following error
    non-static variable this cannot be referenced from a static context
    HttpRequest request = new HttpRequest(connectionSocket);
    Please could someone help.
    Many Thanks
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public static void main(String argv[]) throws Exception
         // Set the port number.
         int port = 6789;
    // Establish the listen socket.
                   String fileName;
                   ServerSocket listenSocket = new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while (true) {
         // Listen for a TCP connection request.
         Socket connectionSocket = listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request = new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread = new Thread(request);
    // Start the thread.
    thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
              socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
         try {
              processRequest();
         } catch (Exception e) {
              System.out.println(e);
    private void processRequest() throws Exception
         // Get a reference to the socket's input and output streams.
         //InputStream is = new InputStream(socket.getInputStream());
         //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
                        new BufferedReader(new InputStreamReader(
                             socket.getInputStream()));
                   DataOutputStream outToClient =
                        new DataOutputStream(
                             socket.getOutputStream());
         // Set up input stream filters.
         requestMessageLine = inFromClient.readLine();
         //BufferedReader br = null;
         // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
                             new StringTokenizer(requestMessageLine);
                   if (tokenizedLine.nextToken().equals("GET"))
                        fileName = tokenizedLine.nextToken();
                        if ( fileName.startsWith("/")==true )
                             fileName = fileName.substring(1);
    File file = new File(fileName);
                        int numOfBytes = (int)file.length();
                        FileInputStream inFile = new FileInputStream(fileName);
                        byte[] fileInBytes = new byte[numOfBytes];
                        inFile.read(fileInBytes);
                        /* Send the HTTP header */
                        outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
                        if (fileName.endsWith(".jpg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".jpeg"))
                             outToClient.writeBytes("Content-Type: image/jpeg\r\n");
                        if (fileName.endsWith(".gif"))
                             outToClient.writeBytes("Content-Type: image/gif\r\n");
                        if (fileName.endsWith(".html"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        if (fileName.endsWith(".htm"))
                             outToClient.writeBytes("Content-Type: text/html\r\n");
                        outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
                        outToClient.writeBytes("\r\n");
                        /* Now send the actual data */
                        outToClient.write(fileInBytes, 0, numOfBytes);
                        socket.close();
                   else
                   System.out.println("Bad Request Message");
                   todaysDate = new Date();          
                   try {
                        FileInputStream inlog = new FileInputStream("log.txt");
                        System.out.println(requestMessageLine + " " + todaysDate );
                        FileOutputStream log = new FileOutputStream("log.txt", true);
                        PrintStream myOutput = new PrintStream(log);
                        myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
                   catch (IOException e) {
                   System.out.println("Error -> " + e);
                   System.exit(1);
    socket.close();

    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class MultiWebServer
    public MultiWebServer(){
    try{
    // Set the port number.
    int port=6789;
    // Establish the listen socket.
    String fileName;
    ServerSocket listenSocket=new ServerSocket(port);
    // Process HTTP service requests in an infinite loop.
    while(true){
    // Listen for a TCP connection request.
    Socket connectionSocket=listenSocket.accept();
    // Construct an object to process the HTTP request message.
    HttpRequest request=new HttpRequest(connectionSocket);
    // Create a new thread to process the request.
    Thread thread=new Thread(request);
    // Start the thread.
    thread.start();
    }catch(IOException ioe){
    }catch(Exception e){
    public static void main(String argv[]) throws Exception
    new MultiWebServer();
    final class HttpRequest implements Runnable
    final static String CRLF = "\r\n";
    Socket socket;
    String requestMessageLine;
    String fileName;
    Date todaysDate;
    // Constructor
    public HttpRequest(Socket socket) throws Exception
    this.socket = socket;
    socket = null;
    // Implement the run() method of the Runnable interface.
    public void run()
    try {
    processRequest();
    } catch (Exception e) {
    System.out.println(e);
    private void processRequest() throws Exception
    // Get a reference to the socket's input and output streams.
    //InputStream is = new InputStream(socket.getInputStream());
    //DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    BufferedReader inFromClient =
    new BufferedReader(new InputStreamReader(
    socket.getInputStream()));
    DataOutputStream outToClient =
    new DataOutputStream(
    socket.getOutputStream());
    // Set up input stream filters.
    requestMessageLine = inFromClient.readLine();
    //BufferedReader br = null;
    // Get the request line of the HTTP request message.
    String requestLine = null;
    // Display the request line.
    System.out.println();
    System.out.println(requestLine);
    StringTokenizer tokenizedLine =
    new StringTokenizer(requestMessageLine);
    if (tokenizedLine.nextToken().equals("GET"))
    fileName = tokenizedLine.nextToken();
    if ( fileName.startsWith("/")==true )
    fileName = fileName.substring(1);
    File file = new File(fileName);
    int numOfBytes = (int)file.length();
    FileInputStream inFile = new FileInputStream(fileName);
    byte[] fileInBytes = new byte[numOfBytes];
    inFile.read(fileInBytes);
    /* Send the HTTP header */
    outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
    if (fileName.endsWith(".jpg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".jpeg"))
    outToClient.writeBytes("Content-Type: image/jpeg\r\n");
    if (fileName.endsWith(".gif"))
    outToClient.writeBytes("Content-Type: image/gif\r\n");
    if (fileName.endsWith(".html"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    if (fileName.endsWith(".htm"))
    outToClient.writeBytes("Content-Type: text/html\r\n");
    outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
    outToClient.writeBytes("\r\n");
    /* Now send the actual data */
    outToClient.write(fileInBytes, 0, numOfBytes);
    socket.close();
    else
    System.out.println("Bad Request Message");
    todaysDate = new Date();
    try {
    FileInputStream inlog = new FileInputStream("log.txt");
    System.out.println(requestMessageLine + " " + todaysDate );
    FileOutputStream log = new FileOutputStream("log.txt", true);
    PrintStream myOutput = new PrintStream(log);
    myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
    catch (IOException e) {
    System.out.println("Error -> " + e);
    System.exit(1);
    socket.close();

  • 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.

  • Another question: non-static variable super cannot be referenced from ...?

    class a
    int i;     
    int j=2;
    a(int i)
    this.i=i;
    public class b extends a
         b()
         super(8);     
    public static void main(String args[])
    b test=new b();
    System.out.print(test.i);
    test.j=1;
    System.out.print("test.j="+test.j);
    System.out.print("super.j="+super.j);
    b.java:28: non-static variable super cannot be referenced from a static context
    System.out.print("super.j="+super.j);
    ^
    1 error
    thanks

    You cannot call "super" from a static context. Just like you can't use "this" or call any non-static methods in a static context.
    Try with test.super.j, although I'm not sure if it works. But you can call super.j in a non-static context, e.g. in your constructor, or in a non-static method.

Maybe you are looking for

  • Error while migrating BLOB data

    Hi , I am migrating the data from oracle to oracle and both soruce and target tables have BLOB type field. I am getting error when I am executing the interface with these blob fields. But My interface is successfull if I am not maaping this blob file

  • MacBook Pro's HD died. How do DE-AUTHORIZE?

    Hello all. I have authorized a total of 3 out of 5 macs for my iTunes Store Account to play media - an iMac, a Mac mini and a MacBook Pro. Recently the *MacBook Pro's hard disk "died totally"*, no way to boot up, if boot from another Startup Disk or

  • Problem opening a query in BEx Analyzer 7.10

    Hello, we have problems with the BEx Analyzer, an empty screen is displayed when we open a query. I'm going to explain the steps: We open Analyzer, goto open query, logon into BW window appears and then, before the screen to select query from an Info

  • "Disk almost full" after taking iBook to Apple store....

    ....to get a new hard drive. My HD decided to quit (after only 2 yrs), took it to Apple, they sent it out, and replaced the HD. Now my iBook's back, and I keep getting "Startup disk almost full". Wouldn't everything be wiped out when a hard drive is

  • Testing for division by zero

    This program consists of 2 classes. The getRating method performs actual calculations based on the below values. The program runs OK, until you test it when dividing by zero. I am trying to return 0 if there is division by zero. I don't think I am ap