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

Similar Messages

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

  • How to access the int variable in the inner class

    hi all,
    i can't access the int variable in the inner class. can any one help me
    int count = 0;
    MouseMoveListener mouseMove = new MouseMoveListener() {
         public void mouseMove(MouseEvent e) {
              count1++;
              System.out.println(count);
    };how to access count variable
    thanks

    for this how can i access the countIf the count variable is a local variable you can't access it from within the
    inner class. Make it a member variable of the outer class instead:public class Outer {
       private int count;
       MouseMoveListener mouseMove= new MouseMoveListener() {
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }Alternatively, if you don't need that count variable anywhere else, you
    could simply make it a member variable of the inner class itself:public class Outer {
       MouseMoveListener mouseMove= new MouseMoveListener() {
          private int count;
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }kind regards,
    Jos

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

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

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

  • Auto-complete not working on variables/functions within a class in FlashBuilder 4.5

    Hi all,
    I'm using Flash Builder 4.5 (not burrito), and I'm not getting auto-complete on variables or functions within the class I'm working in.  It will auto-complete classes, and even variables within another variable, but not a variable within that class.
    As an example, let's say I have a class with this var:
    private var myDate:Date = new Date();
    If I start typing myD, I can't get myDate to autocomplete.  But once I type myDate., I'll get auto-complete for all the variables/functions in the Date class.
    I've tried re-installing FlashBuilder and switching workspaces, but with no luck.
    Also tried creating a brand new test project, but it didn't work there either.
    Anyone have any ideas what might be wrong?
    Thanks!

    Hi,
    After you type "myD" If u press cntrl + space it should auto-complete to myDate. Please raise a bug in http://bugs.adobe.com/flex with the sample project as i am not able to reproduce.
    On the other hand if you were expecting code hint to show up as soon as you type "myD" (without pressing cntrl+space) , Please follow the below step.
    Go to Window -> Preferences -> Flash Builder -> Editor
    check the "use additional custom triggers" check box. Leave the keys as default value .
    That should work for you .

  • JavaFX accessing Java Inner Classes

    We have LOTS of common Java classes that look like this...
    public class X {
        public class Y {
            public static final String Z = "ZzZZZzzZzzZzzZz";
    }So in JAVA we can access them like this...
    public String z = X.Y.Z;But in JavaFX I CAN'T do this...
    var z : X.Y.Z;The compiler says +"non-static class com.myproject.X.Y cannot be referenced from a static context"+
    Tell me it aint so, please :)

    Galien, I doubt AndrewHughes can / want to change all the existing Java classes...
    I tried to reproduce (I did) and found a workaround...
    Java class (X.java):
    public class X
        public static final String ZX = "ZzZZZzzZzzZzzZzXX";
        public class Y
            public static final String ZY = "ZzZZZzzZzzZzzZzYY";
        public static void main(String[] args)
          new A();
    class A
      A()
        System.out.println(X.Y.ZY);
    }OK, it works...
    JavaFX code: var z = X.Y.Z;(and not var z: X.Y.Z; since Z isn't a type...) Error "+non-static class X.Y cannot be referenced from a static context+". Mmmm...
    Trying var z = X.ZX; works, of course.
    Looking at the generated class files, I thought of a workaround: var z = X$Y.ZY;Yay! it works! :-D

  • How can a textInput variable access a document Class?

    I have a document class which creates a body of text on-the-fly at runtime.  I am trying to figure out (though I haven't taken any steps to do so yet) how to use a textinput field on the stage of a Flash document that calls the Document Class "MyClass" (just for example's sake").  The class file is MyClass.as and is located in the same directory as the FLA and resultant SWF.  I would like that textInput.text value to change the body text of the MyClass text.  The reason I am using MyClass is because I am performing special visualizations with the text that are encapsulated in MyClass.
    Thanks in advance for any feedback.
    -markerline

    I hadn't realized that this import was what was necessary.  Thank you.  However now with the imported property and my EnterFrameEvent, the rendered text is still not updating.
    Here is my complete Document Class:
    package
        import away3d.containers.ObjectContainer3D;
        import away3d.extrusions.TextExtrusion;
        import away3d.primitives.TextField3D;
        import flash.events.Event;
        import flash.display.MovieClip;
        import wumedia.vector.VectorText;
        import flash.text.TextField;
        import flash.text.TextFieldType;
        public dynamic class FontExtrusionDemo extends Away3DTemplate
            [Embed(source="Fonts.swf", mimeType="application/octet-stream")]
            protected var Fonts:Class;
            protected var container:ObjectContainer3D;
            protected var extrusion:TextExtrusion;
            protected var text:TextField3D;
            public var txtFld:TextField;
            public var myString:String;
            public function FontExtrusionDemo()
                super();
            protected override function initEngine():void{
                super.initEngine();
                this.camera.z=0;
                VectorText.extractFont(new Fonts());
            public function setString():void{
                this.myString=myString;
                txtFld= new TextField();
                txtFld.x=txtFld.y=20;
                txtFld.width =100;
                txtFld.height=20;
                txtFld.border=txtFld.background=true;
                txtFld.type=TextFieldType.INPUT;
                addChild(txtFld);
                stage.focus=txtFld;
            protected override function initScene():void{
                super.initScene();
                myString="1";
                setString();
                text = new TextField3D("Vera Sans",{
                    text:myString,
                    align: VectorText.CENTER}
                extrusion = new TextExtrusion(text, {
                    depth: 10,
                    bothsides:true}
                container = new ObjectContainer3D(text, extrusion, { z:300 });
                scene.addChild(container);
            protected override function onEnterFrameEvent(event:Event):void{
                super.onEnterFrameEvent(event);
                text = new TextField3D("Vera Sans",{
                    text:String(txtFld.text),
                    align: VectorText.CENTER}
                extrusion = new TextExtrusion(text, {
                    depth: 10,
                    bothsides:true}
                //container = new ObjectContainer3D(text, extrusion, { z:300 });
                //scene.addChild(container);  // IF I UNCOMMENT THIS THEN A NEW CHILD WILL BE ADDED AT EVERY FRAME, which is not desired.
                container.rotationY=(container.rotationY+1)%360;
                if (container.rotationY>90&&container.rotationY<270){
                    text.screenZOffset=10;
                } else {
                    text.screenZOffset=-10;

  • 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

  • Pesky Inner Classes

    Hi folks,
    Ok, so the title is a bit misleading, it's not inner classes that are pesky, more the fact that there is something I don't understand about them. I'd really appreciate some help.
    What I would like to do is to create some JButtons, which are identical except for a slight difference in their actions when clicked.
    Basically I'm trying to create a panel which displays a few JTextFields, each with a button associated with it. Clicking the button will spring a JFileChooser that allows the user to select a file. The url of this file will then be displayed in the textfield.
    Each of these text fields is a field of the class I am working on. I wanted to avoid writing separate methods to create each of these JButtons as they do pretty much the same thing. So...here is the method I wanted to use to build them:
         JButton buildBrowseButton(JTextField targetTextField)
              JButton browseButton = new JButton("Browse...");
              browseButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        File targetFile = getTargetFileWithChooser();
                        targetTextField.setText(targetFile.getAbsolutePath());
         }I thought I would just create the text areas, pass them as arguments to the above function and get the associated 'Browse' button back.
    Except I get the following error message from my IDE:
    Cannot refer to a non-final variable targetTextField inside an inner class defined in a different methodDo I really have to write a slightly different method for each button? Or am I missing something that would make my life a lot easier?
    As I say, i'd really appreciate some help with this - and thank you for reading through this lengthy post!

    As the error message says, you can't refer to a non-final local variable from an inner class. In your case it is really simple to fix though:
    // Make the targetTextField argument final:
    JButton buildBrowseButton(final JTextField targetTextField)
    }

  • Catch-22: need to assign a local variable within an anonymous class

    static boolean showMessage(Window parent, String button0, String button1)
        throws HeadlessException {
              final Window w = new Window(parent);
              Panel p = new Panel(new GridBagLayout());
              final Button b[] = new Button[]{new Button(button0), (button1 != null) ? new Button(button1) : (Button)null};
              boolean rval[]; //tristate: null, true, false
              w.setSize(100, 50);
              w.setVisible(true);
              //add b[0
              gbc.fill = GridBagConstraints.HORIZONTAL;
              gbc.gridx = 0;
              gbc.gridy = 3;
              p.add(b[0], gbc);
              //add b[1]
              if (button1 != null) {
                   gbc.fill = GridBagConstraints.HORIZONTAL;
                   gbc.gridx = 1;
                   gbc.gridy = 3;
                   p.add(b[1], gbc);
              w.add(p);
              w.pack();
            w.setVisible(true);
            //actionListener for button 0
              b[0].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (e.getSource() == b[0]) {
                                  w.setVisible(false);
                                  rval = new boolean[1];
                                  rval[0] = true;
              //actionListener for button 1
              if (button1 != null) {
                   b[1].addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) {
                                  if (e.getSource() == b[1]) {
                                       w.setVisible(false);
                                       rval = new boolean[1];
                                       rval[0] = false;
            while (true) {
                 try {
                      if (rval[0] == true || rval[0] == false) //should trigger NullPointerException
                           return rval[0];
                 } catch (NullPointerException e) { }
         }catch-22 is at
    rval = new boolean[1];
    rval = false;javac whines: "local variable rval is accessed from within inner class; needs to be declared final"
    How do I assign to rval if it's declared final?
    Or at the very least, how do I get rid of this error (by all means, hack fixes are okay; this is not C/C++, I don't have to use sanity checks)?
    I'm trying to make a messagebox in java without using JOptionPane and I'm trying to encapsulate it in one method.
    And I'm far too lazy to make a JNI wrapper for GTK.

    dcminter wrote:
    How do I assign to rval if it's declared final?You don't and you can't. You're not allowed to assign to the local variable of the outer class for extremely good reasons, so forget about trying.
    Or at the very least, how do I get rid of this errorIf you don't want the side effect, then just use an inner class variable or a local variable.
    If you want the side effect then use a named class and provide it with a getter and setter.
    Finally, in this specific case because you're using an array object reference, you could probably just initialise the array object in the outer class. I.e.
    // Outer class
    final boolean[] rval = new boolean[1];
    // Anonymous Inner class
    rval[0] = true; // No need to intialize the array.
    I declared it as an array so that it would be a tristate boolean (null, true, false) such that accessing it before initialization from the actionPerformed would trigger a NullPointerException.
    Flowchart:
    is button pressed? <-> no
    |
    V
    Yes->set and return
    Is there a way to accomplish this without creating a tribool class?

  • Custom class loader and local class accessing local variable

    I have written my own class loader to solve a specific problem. It
    seemed to work very well, but then I started noticing strange errors in
    the log output. Here is an example. Some of the names are in Norwegian,
    but they are not important to this discussion. JavaNotis.Oppstart is the
    name of my class loader class.
    java.lang.ClassFormatError: JavaNotis/SendMeldingDialog$1 (Illegal
    variable name " val$indeks")
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at JavaNotis.Oppstart.findClass(Oppstart.java:193)
    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 JavaNotis.SendMeldingDialog.init(SendMeldingDialog.java:78)
    at JavaNotis.SendMeldingDialog.<init>(SendMeldingDialog.java:54)
    at JavaNotis.Notistavle.sendMelding(Notistavle.java:542)
    at JavaNotis.Notistavle.access$900(Notistavle.java:59)
    at JavaNotis.Notistavle$27.actionPerformed(Notistavle.java:427)
    JavaNotis/SendMeldingDialog$1 is a local class in the method
    JavaNotis.SendMeldingDialog.init, and it's accessing a final local
    variable named indeks. The compiler automatically turns this into a
    variable in the inner class called val$indeks. But look at the error
    message, there is an extra space in front of the variable name.
    This error doesn't occur when I don't use my custom class loader and
    instead load the classes through the default class loader in the JVM.
    Here is my class loading code. Is there something wrong with it?
    Again some Norwegian words, but it should still be understandable I hope.
         protected Class findClass(String name) throws ClassNotFoundException
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         private byte[] loadClassData(String name) throws ClassNotFoundException
             ByteArrayOutputStream ut = null;
             InputStream inn = null;
             try
                 JarEntry klasse = arkiv.getJarEntry(name.replace('.', '/')
    + ".class");
                 if (klasse == null)
                    throw new ClassNotFoundException("Finner ikke klassen "
    + NOTISKLASSE);
                 inn = arkiv.getInputStream(klasse);
                 ut = new ByteArrayOutputStream(inn.available());
                 byte[] kode = new byte[4096];
                 int antall = inn.read(kode);
                 while (antall > 0)
                     ut.write(kode, 0, antall);
                     antall = inn.read(kode);
                 return ut.toByteArray();
             catch (IOException ioe)
                 throw new RuntimeException(ioe.getMessage());
             finally
                 try
                    if (inn != null)
                       inn.close();
                    if (ut != null)
                       ut.close();
                 catch (IOException ioe)
         }I hope somebody can help. :-)
    Regards,
    Knut St�re

    I'm not quite sure how Java handles local classes defined within a method, but from this example it seems as if the local class isn't loaded until it is actually needed, that is when the method is called, which seems like a good thing to me.
    The parent class is already loaded as you can see. It is the loading of the inner class that fails.
    But maybe there is something I've forgotten in my loading code? I know in the "early days" you had to do a lot more to load a class, but I think all that is taken care of by the superclass of my classloader now. All I have to do is provide the raw data of the class. Isn't it so?

  • Outer Class Accessing Inner Classes Variables

    Hi Everyone,
    Should an outer class directly access the private member variables of its inner class? Or should it get their values by calling an appropriate 'getXXX()' method?
    Just wondering.
    Thx.

    If the outer class trys to access the variable that is declared in the inner class with in a class and outside the method, then it can access in the following example
    class outer
         private int x=10;
         class inner
              int y=20;
         public void getOutput()
              inner in=new inner();
              System.out.println("The value of y is" +in.y);
         public static void main(String args[])
              outer out=new outer();
              out.getOutput();
    };

Maybe you are looking for