Local variable can't be accessed from inner class ???????? Why ??????

Plesae help, help, help. I have no idea what to do with this bug.........
<code>
for ( int i = 0; i <= 2; i++ ) {
for ( int j = 0; j <= 2; j++ ) {
grids[i][j] = new MyButton ();
grids[i][j].setBorder(but);
getContentPane().add(grids[i][j]);
MyButton sub = grids[i][j];
sub.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ( sub.getState() == 0 ) {
     sub = new MyButton( (Icon) new ImageIcon(imageFile));
     if ( imageFile.equals("cross.jpg") ) {
          sub.changeState(1);
     else {
          sub.changeState(2);
</code>
The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

OK, now I changed my code to this :
for ( int i = 0; i <= 2; i++ ) {
  for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    grids[i][j].addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        if ( grids[i][j].getState() == 0 ) {
           grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
          if ( imageFile.equals("cross.jpg") ) {
           grids[i][j].changeState(1);
          else {
          grids[i][j].changeState(2);
[/cpde]
Thanks for your advice !!!!!!
Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

Similar Messages

  • Access from inner class

    hi all,
    I have one frame with two panels inside, code likes the following:
    public class ShowChart extends JFrame{
    Container f = getContentPane();
    f.setLayout(new BorderLayout());
    JPanel chart=new drawChart();
    JPanel setting=new settingChart(chart);
    f.add(setting,java.awt.BorderLayout.WEST);
    f.add(chart);
    class drawChart extends JPanel(){
    setTableWidth(int w){...}
    class settingChart extends JPanel(){
    drawChart chart;
    pubic settingChart(drawChart c){
    chart=c;
    JTextField width = new JTextField("9",4);
    add(width);
    JButton change = new JButton("Change");
    change.addActionListener(new changeHandle(chart));
    add(change);
    change.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event){
    int w = (int)Double.parseDouble(width.getText());
    chart.setTableWidth(w);
    Compilling error: local virable chart is accessed from within inner class, need to be declared as final. chart.setTabelWidth(w);
    how can i deal with this problem? (i know it will be ok if i messy all the viriables and method of settingChart into the ShowChart class, but it seems not a nice way...)
    thanks
    dejie

    Below is an example of an inner class field 'masking' the name of the outerclass field. So to access the outerclass you use OuterClass.this and then the field of that class...
    public class OuterClass {
      private int value = 1;
      class InnerClass {
        int value = 2;
        public InnerClass() {
          doStuff();
        void doStuff() {
          this.value++;
          OuterClass.this.value++;
    }Hope that helps...

  • Accessing Enclosing Class Members From Inner Class Subclass

    I have the following scenario that I cannot get to work. Notice the comments in B.doWork() for the problem code. In B.doWork(), how do I access m_strA?
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // How do I access m_strA within B's doWork() method?  The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);

    The whole point is that B is not an inner class of A
    so it does not have access to A's member variables.
    Eventhough B extends an inner class of A, that does
    not make B an inner class of A. That is in the JLS,
    but not so elegantly as I have put it, hehe.
    If B were an innerclass of InnerA, then it would
    qualify to access A's member variables.OK, I think that you are finally getting through to my thick skull on this one. Let me restate and get your check-off on my understanding of the situation.
    The only classes with access to A's this reference are A and inner classes of A that are found within the definition of A. So, despite the fact that A and B are in the same package (and B should have access to A's non-private members because B and A are in the same package), and despite the fact that we would normally state that B "is a" InnerA (which is an inner class of A and would have access to a reference to the A.this reference), B is not allowed access to A.this (because B "is not really a" InnerA in the same way that the anonymous implementation of InnerA "is a" InnerA). However, nothing would prevent me from giving B access to a reference of the enclosing A as long as it was done via a method of InnerA, and as long as the implementation of that method is contained in A's implementation.
    Does this "access" rule realy make sense? Are you aware of the justification for this rule? Or is the justification stated in the JLS? I would think that the compiler ought to be able to figure this kind of thing out and allow it. It seems to me the fact that I defined B in the way that I did, and the fact that B "is a" InnerA, implies that I desired a fairly tight relationship to A. In fact, I desired the exact relationship that exists for the anonymous implementation of InnerA.
    The following is a modified version of my original example that runs as I originally wanted it to, but works around the access rules discussed on this forum thread:
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
              /** added to allow implementors of InnerA that are not enclosed in A's class definition to have access to the enclosing class */
              public A myEnclosingInstance ()
                        return (A.this);
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
                   // added myEnclosingInstance() to get functionality desired above
                   myEnclosingInstance().m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);
    }

  • I have an iTunes account where I have downloaded Digital movies & I am able to see the list on the desktop of the original downloads. When I log on another device with my login I do not see my list to access them. Why can't I access from another device

    I have an iTunes account where I have downloaded Digital movies & I am able to see the list on the desktop of the original downloads. When I log on another device with my login I do not see my list to access them. Why can't I access from another device

    Hey GingCarv,
    Great question. You'll want to download the movies from your purchase history. The following article explains how to do so:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store
    http://support.apple.com/kb/HT2519
    Note: At this time, movies are not available for automatic downloads.
    Thanks,
    Matt M.

  • How to access super of enclosing class from inner class?

    Hello,
    I'd like to access Base.foo() from inner class in overridden Improved.foo(), but seem unable:
    public class InnerSuper {
         public static class Base {
              protected int foo() {
                   return 1;
         public static class Improved extends Base {
              @Override
              protected int foo() {
                   return Integer.parseInt(new Object () {
                        public String toString() {
                             return "1"+foo() ;
                   }.toString());
         public static void main(String[] args) {
              System.out.println(new Improved().foo());
    }The code above does not work, as it recursively calls Improved.foo() where I'd like it to call Base.foo(). What syntax construct should I use? Improved.this would be the same thing, Improved.super does not exist.
    I came up with a work around: adding a method baseFoo() to Improved and call that in the inner class:
       int baseFoo() {
          return super.foo();
       } but remain wondering if that is necessary?

    Indeed, Improved.super.foo() is allowed. My Eclipse syntax highlighting seems to have the same opinion as you: "are you sure you want to write that kind of code?" and leaves the read underlining for a syntax error on for just a second longer.
    This is where I am now:
         public static class DeferredExecSubroutineCall extends SubroutineCall {
              RelayExecutor relay;
              public DeferredExecSubroutineCall(RelayExecutor relay) {
                   this.relay = relay;
              @Override
              protected String execute(final IFDSOC fd, final String commandText) {
                   Future<String> f = relay.submit(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                             return DeferredExecSubroutineCall.super.execute(fd, commandText);
                   try {
                        return f.get();
                   } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                   } catch (ExecutionException e) {
                        if (e.getCause() instanceof RuntimeException) {
                             throw (RuntimeException) e.getCause();
                        } else {
                             throw new RuntimeException(e.getCause());
         }which is my current effort of adding concurrency to an existing project. I find it quite elegant but I am interested to hear from you...

  • Accessing the inner class written inside the method

    Hi all,
    Can any of you tell me how to access the inner class's method which is written inisde the outer class's method. THe code fragment is
    class Outer
    private static final int ID = 3;
    public String name;
    public void methodA( int nn )
    final int serialN = 11;
    class inner
    void showResult()
    System.out.println( "Rslt= "+ID );
    } // end class inner
    // new inner().showResult();
    } // end methodA
    class Sample
    public static void main(String a[])
    //access the showResult of Inner class??
    Thanks in advance.
    aah

    class Outer {
      private static final int ID = 3;
      public String name;
      public void methodA( int nn ) {
        final int serialN = 11;
        class inner {
          void showResult() {
            System.out.println( "Rslt= "+ID );
        } // end class inner
        new inner().showResult();
      } // end methodA
    class Sample {
      public static void main(String a[]) {
        new Outer().methodA(5);
    }

  • Inheriting from inner classes

    TIJ has a section on inheriting from inner classes, but the author didn't illustrate a scenario. What could be the possible usage? Why would one want to only inherit the inner case, but have to initialize the outter class (which it doesn't want to inherit)?
    Example code in the book:
        //: c08:InheritInner.java
        // Inheriting an inner class.
        class WithInner {
          class Inner {}
        public class InheritInner extends WithInner.Inner {
          //! InheritInner() {} // Won't compile
          InheritInner(WithInner wi) {
            wi.super();
          public static void main(String[] args) {
            WithInner wi = new WithInner();
            InheritInner ii = new InheritInner(wi);
        } ///:~

    I've certainly never felt the need to extend inner
    classes. As far as I'm concerned, inner classes are
    great for certain uses, all of which involve them
    being private. I've yet to find a scenario where a
    non-private inner class is preferable to a 'proper'
    class.To make the outer class act as a factory. The inner class is public but the constructors are private.

  • Clarification about inner class - why use it?

    hi all
    i just have a request to get some clarification on inner class. why do we use it and is it common to use it? thanks.

    hi all
    i just have a request to get some clarification on
    inner class. why do we use it and is it common to use
    it? thanks.It is realtively common. You may use one if you need to implement a class that's only relevant to one other class, like a data container or EventListener. Since it's probably interlocking tightlyx with its "outer" class, but doesn't need to be in reach of any other classes, its visibility can be confined to the outer class itself. Plus, objects from inner classes - if not declared static - are always tied to the existance of an outer class instance.

  • Local variable accessed within inner class

    Hey everybody,
    My program keeps telling me that it wont work because one of my methods is calling a local variable inside an inner class. Does anyone know what this means and how to fix it?
    Heres the code:
    public class SliderExample extends JPanel{
    int value=0;
    public SliderExample(int imw, int imh, Image img, BufferedImage buf, Graphics2D biCon){
    super(true);
    this.setLayout(new BorderLayout());
    JSlider slider= new JSlider(JSlider.HORIZONTAL,0,imw,25);
    slider.setMinorTickSpacing(10);
    slider.setMajorTickSpacing(100);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    JButton redraw= new JButton("Scroll");
    redraw.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ev){
    reDraw(slider,img,buf,biCon,imw,imh);
    add(slider,BorderLayout.CENTER);
    add(redraw,BorderLayout.AFTER_LINE_ENDS);
    public void reDraw(JSlider slid, Image im, BufferedImage bf, Graphics2D biC, int iw, int ih){
    value=slid.getValue();
    Graphics g= getGraphics();
    g.drawImage(im,value,0,iw,ih,this);
    g.drawImage(bf,value,0,iw,ih,this);
    biC.drawImage(bf,value,0,iw,ih,this);
    Any ideas???
    THanks,
    Rick

    Its getting them from another class thats calling the mothod to construct the slider bar with dedraw button. Thats a pretty big class but I will post the code where I called the method:
    public class Process extends JFrame implements MouseListener, MouseMotionListener{
    private int [][] points;
    private int [] lengths={0};
    private int [] bin;
    private String imstr;
    private String imsav;
    private int imgw=658;
    private int imgh=512;
    private int xArrayPos=0;
    private int yArrayPos=0;
    private int xpos=0;
    private int ypos=0;
    private int xprev;
    private int yprev;
    private int xadd;
    private int yadd;
    private String filstr;
    Image image;
    SimpleGUI gui;
    BufferedImage buffer;
    Graphics2D biContext;
    Graphics2D g2;
    BufferedImage last;
    Graphics2D lastContext;
    public Process(){
    JFrame slideFrame = new JFrame("Please slide to scroll image");
    slideFrame.setContentPane(new SliderExample(imgw, imgh,image,buffer,biContext));
    slideFrame.pack();
    slideFrame.setVisible(true);
    Thats what anything having to do with that function in the other class that calls the Slider Class.
    Do you know how I can fix this??
    Thanks,
    Rick

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

  • Can mail be accessed from a remote machine

    If multiple mail accounts are set up on lion server (students in a school), can these accounts be accessed from the outside world by the students? Preferrebly via a web browser.
    Would this be possible or would there be any other method of accessing mails without a fixed machine with a VPN?
    Doey

    The Server applicaiton will allow you to tick a box to enable webmail under the "Mail" configuration area.
    This will use either the default self-signed SSL certificate, or, whichever certificate you nominate, to then enable the Apache2 web server to listen on 443 and re-direct traffic to your.host.name:443/webmail to the included Roundcube installation.
    Roundcube is a popular (free) webmail package that is pre-configured on Lion Server -- all you should need to do is correctly enable users (one note on that, see below), configure the Mail service itself, and enable Webmail via the tick box.  I've done this, it works.
    The note on enabling users:  There are some configurations whereby the type of password storage used by Lion Server is not compatible with Mail/Webmail -- I can't recall off the top of my head what these are, but, when I created and administered users, there was a warning.  And indeed, if I tried to sign in as certain users, it would not work.  I had to reset the password and it worked fine.
    In short, though, the webmail installation is pretty slick.  Lion is using Dovecot for IMAP/POP, Postfix for SMTP and Roundcube for Webmail.
    If you REALLY want to please your users, you'll want to enable Server Side Mail Filters -- which is Apple talk for Sieve, a fantastic way to sort and process mail on the server side automatically as mail arrives.  The Roundcube webmail setup has the GUI for this built in, under the Filters area.
    Hope that helps!

  • Why eclipse gives me warning if I access in inner class a parent  field ?

    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miro

    miro_connect wrote:
    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miroWhat happens if you remove the modifier? (That is uses default)

  • JCX access from java class

    Is it possible to access jcx from java class ?
    from jpf i am calling java class which inturn calls jcx and
    i am getting nullpointer exception at jcx call in java class
    waiting for solution...
    thanks,
    sridhar

    Shrishar,
    Unfortunately in the current release controls cannot be accessed from stand
    alone java classes. You can create a custom control which can invoke the jcx
    and be invoked from within the jpf.
    Regards,
    Raj Alagumalai
    Backline Workshop Support
    "sridhar" <[email protected]> wrote in message
    news:4083d449$[email protected]..
    >
    Is it possible to access jcx from java class ?
    from jpf i am calling java class which inturn calls jcx and
    i am getting nullpointer exception at jcx call in java class
    waiting for solution...
    thanks,
    sridhar

  • Can enclosing instance for an inner class be null?

    I have a class Solution, which defines an inner class, SolutionStep.
    In a third class I construct several SolutionStep objects, and later use them to construct a Solution.
    In this third class I have statements like this:
    Solution solution = null;
    aCollection.add(solution.new SolutionStep(arg1, arg2);
    This has been working fine, but recently a customer reported an error,which seems to be a NullPointerException at the line above.
    Now that I look at this code, I'm not very happy about it and I'll clean it up, but I am left with the basic question of whether what I'm doing is legal. Can the enclosing instance used to construct an inner class be null? I have not been able to find a definitive answer.
    Any help appreciated.

    Yes, you're right, I dropped a parenthesis. Sorry.
    The offending statement is actually
    aCollection.add(solution.new SolutionStep(arg1,
    arg2));
    And that is certainly legal. The inner class does not
    need to be qualified when it's constructed in the
    context of an enclosing instance.Very interesting.
    The following code demonstrates this....
        class Solution
            class SolutionStep
                public SolutionStep()
        public class ThirdClass
            static public void main(String[] args)
            Solution solution = null;
            //Solution solution = new Solution();  // This produces no null exception.
            Solution.SolutionStep s = solution.new SolutionStep();
    Using jikes and javac doesn't change the behavior so that means it is VM rather than compiler specific.
    I am using 1.4.2_04 on windows and I get the null pointer exception.
    Looking at the javap output suggests that invokespecial has to be checking this (although I could have overlooked something when I checked.)
    This probably comes from the following in the VM spec under invokespecial...
    Otherwise, if objectref is null, the invokespecial instruction throws a NullPointerException.

  • After "Replace with clip" the original clip can not be deleted from the project - why?

    After using "replace with clip" to replace clip A in the timeline with a new clip B , clip A can not be deleted from the project anymore.
    If you try to delete clip A, you get a warning, that it still has references in one or more sequences.
    If you continue and delete clip A, it seems to be deleted - at first!
    Unfortunately if you save and reopen the project, clip A is restored to folder "Recovered clips".
    It's not possible to really delete it.
    I also did not find a way to unlink clip B from A .
    The only thing you can do, is to revert the change by "Restore Unrendered" in the clip context menu. But that's obviously not helping
    I dont know if this is a bug or a feature. I understand, that it can be useful to undo the "replace clip" function, but why would anyone not want to be able to delete the original clip at all?
    help how to fix this problem is greatly appreciated!
    I use Premiere Pro CC 2014.2 (Win7 64bit)

    I'm sure it has nothing to to with other sequences.
    You can easily reproduce this behaviour:
    1. create a new project
    2. import 2 clips and name them "A" and "B"
    3. put "A" in the timeline
    4. ALT-drag "B" over "A" in the timeline (or right-click "A" in the timeline while selecting "B" in the project files and select "replace with clip ... from bin")
    5. delete "A" from the project files
    6. save and close project
    7. reopen project
    => "A" reappears in "Recovered clips" and can not be deleted.

Maybe you are looking for