5

Why does SWING always force me to mark some particular objects as final ? Since this sometimes makes things a bit difficult, Is there a way to avoid this ?

(INCOMPLETE EXAMPLE) where it forces me to mark the IExchangeSource variable as final:

public class MainFrame {

private final JTextArea textArea = new JTextArea();


public static void main(final IExchangeSource s) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new MainFrame(s);
        }
    });
}
public MainFrame(final IExchangeSource s) {
    //build gui
    s.update();
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • 3
    Can you give an example? Are you talking about using variables from a surrounding method in an anonymous inner class? Because there is nothing in Swing itself that enforces you to make variables `final`. – Jesper Jan 05 '12 at 15:36
  • 2
    I bet that you are using anonymous inner class. – Eng.Fouad Jan 05 '12 at 15:37

1 Answers1

18

This has nothing to do with Swing, nothing at all. You should show your code that has an example of this, but likely you are using an inner class, possibly an anonymous inner class, and if you use these and try to use variables inside the inner class that are local to an enclosing method (or other block such as a constructor), then you are requried to make these variables final or promote them to class fields. Again this is a Java requirement, not a Swing requirement.

A Swing example:

public MyConstructor() {
   final int localIntVar = 3;  // this must be final

   myJButton.addActionListener( new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
         // because you use the local variable inside of an anon inner class
         // not because this is a Swing application
         System.out.println("localIntVar is " + localIntVar);
      }
   });
}

and a Non-Swing example:

public void myMethod() {
   final String foo = "Hello"; // again it must be final if used in 
                               // an anon inner class

   new Thread(new Runnable() {
      public void run() {
         for (int i = 0; i < 10; i++) {
            System.out.println(foo);
            try {
             Thread.sleep(1000);
            } catch (Exception e) {}

         }
      }
   }).start();
}

There are several tricks to avoid this:

  • Promote the variable to a class field, giving it class scope.
  • Have the anonymous inner class call a method of the outer class. But then, the variable will still need to have class scope.

Edit 2 Anthony Accioly posted an answer with a great link, but then for unknown reasons deleted his answer. I'd like to post his link here, but would love to see him re-open his answer.

Cannot refer to a non-final variable inside an inner class defined in a different method

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks for the answer and yes I was using an inner class (see the example). Sorry for not adding an example at first. – Cemre Mengü Jan 05 '12 at 15:45
  • @Cemre, what do you mean sorry for not posting an example? You have been asked in the past to post an SSCCE with your question. An SSCCE should be included with every question. – camickr Jan 05 '12 at 15:51
  • 2
    @Cemre: you're welcome. I'm not sure why you got the down-votes. We aren't born knowing Java, and if we are all down-voted for ignorance, then we'd all have negative reputations. Up-voted ya to counter-act the downers. – Hovercraft Full Of Eels Jan 05 '12 at 15:52
  • 1
    I understand your point but I was not sure what to include at first and I thought people would know without an example (as it can be seen) since its probably something widely know. I immediately included one upon asked. Why being so harsh ? – Cemre Mengü Jan 05 '12 at 15:54
  • @HovercraftFullOfEels Thanks so much. I guess some people just don't get it or have the patience and respect for others. – Cemre Mengü Jan 05 '12 at 15:57
  • @AnthonyAccioly: why delete your answer? I thought it was great and the link taught me something new! FWIW, I have voted to un-delete it. – Hovercraft Full Of Eels Jan 05 '12 at 15:58