Array inner class (advice from YoGee)

Hello, I am trying to write an array of records, I think it is all OK except for when i try to loop out the results. I get an error in the last for loop at
for (int x=0; x < records.length; x++)
it says record.length has not been initialised.......it hasnt because I dont know what size it is. Even if i hard code in a large enough number I still get a java.lang.NullPointerException error. Any ideas? Code below.
Thanks.
private class Record
private int col1;
private int row1;
private Record(int col1, int row1)
this.col1 = col1;
this.row1 = row1;
private int getCol1()
return col1;
private int getRow1()
return row1;
public void Test()
Record[] records;// = new Record[]; {new Record(1,2), new Record(4,6)};
Record record = null;
Point q1[]= new Point[mbr.getEdge()];
Point q2[]= new Point[mbr.getEdge()];
Point q3[]= new Point[mbr.getEdge()];
Point q4[]= new Point[mbr.getEdge()];
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
Point point = new Point(col, row);
if (shape[col][row] == 255)
//Q1
if (col >= mbr.getCentroid().col && row <= mbr.getCentroid().row)
records = new Record[] {new Record(col, row)};
for (int x=0; x < records.length; x++)
record = records[x];
System.out.println("Record : " + (x+1));
System.out.println("Col1 : " +record.getCol1());
System.out.println("Row1 : " +record.getRow1());
//System.out.println("Row1 : " +quarter1.g);
}

It is reaching the array initalisation, it is just when I try to print out the values i have a problem....anyone know why this might be
private class Record
private int col1;
private int row1;
private Record(int col1, int row1)
this.col1 = col1;
this.row1 = row1;
private int getCol1()
return col1;
private int getRow1()
return row1;
public void Test()
Record[] records;// = new Record[] {new Record(1,2), new Record(4,6)};
Record record = null;
//int q1[]= new int[mbr.getEdge()];
//Point q2[]= new Point[mbr.getEdge()];
//Point q3[]= new Point[mbr.getEdge()];
//Point q4[]= new Point[mbr.getEdge()];
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
if (shape[col][row] == 255)
//Q1
if (col >= mbr.getCentroid().col && row <= mbr.getCentroid().row)
records = new Record[] {new Record(col, row)};
//System.out.println("Col1 : " +record.getCol1());
//System.out.println("Row1 : " +record.getRow1());
System.out.println("here");
}

Similar Messages

  • Setting Array of class field from C++

    Hi,
    Consider I have two class
    Class A{
    B[] bclasses;
    Class B{
    int first;
    int second;
    Now i have
    jclass ACls= env->FindClass("A");
    How to create array of B, get the fields of B, assign value of B and assign array of B from C++ to Java. Please explain with example

    For each B
    -Get the class (do it the first time.)
    -Create the instance
    -Call the construtor
    -Get each member variable.
    -Set the value of each member variable.
    To do A
    -Get the class (do it the first time.)
    -Create the instance
    -Call the construtor
    -Get each member variable.
    -Set the value of each member variable - as an array
    . - Get array class
    . - Create instance
    . - Initialize each array index using the B method above.

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

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Accessing inner classes

    I am making a simple drawing program where the user can draw with the mouse on a jpanel.
    i have my program structure with one big class and two inner classes
    the first inner class creates the panel you can draw on and the mouselistener events to allow a user to draw.
    the second class creates another jpanel that allows you to make a color with the three properties red,green and blue. it also has two buttons. one to set the forground(the color you will draw with) and the other to set the background.
    I can get the forground one to work because i set the color created to a varible and sense there are mouse listners everytime the mouse listener executes it can grab that varible and set the color of the line be drawn.
    my problem is with the background, i can't figure out how to access my first inner class from my second inner class to change the panels background to corspond with the user.
    is there some listener i can apply or a way to change the properties of one inner classes objects from another inner class???
    please help

    I dont knoew if I understand your problem exactly- but if you are wanting to access the first inner class from the second inner class- you can go through the outer class like so:
    public class InnerOuter {
      public InnerOuter() {
      public void test(String s) {
        Inner i = new Inner();
        i.setBackground(s);
      class Inner{
        public String B="inner";
        public void setBackground(String s){
          //do something
      class Inner2{
        public String C="inner2";
        public void setBack2(){
          InnerOuter.this.test("red");
      public static void main(String[] args) {
        InnerOuter innerOuter1 = new InnerOuter();

  • 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 call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • How can i use class reference from an array effeciently?

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

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

  • How to refer the parent class object from an inner class

    Hi,
    I have a class X, which contains an inner private class Y. Class X has a method getY which returns an object of class Y. Class Y has a method getParent. I want to return the object of parent class from this. The code is like this:
    public inerface IY;
    public class X {
    private class Y implements IY {
    public getParent {
    // ... return the object of parent class which created the object of this inner class
    public IY getY() {
    return new Y();
    Can somebody help me with this...

    interface IY {
    public class X {
        private class Y
            implements IY {
            private X parent;
            public Y(X x)
                parent = x;
            public X getParent()
                // ... return the object of parent class which created the object of this inner class
                return parent;
        public IY getY()
            return new Y(this);
    }Filip

  • From sunś Inner Class Exampel

    Hi Have a questions about the exampel
    [http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html]
    public void printEven() {
            //print out values of even indices of the array
            InnerEvenIterator iterator = this.new InnerEvenIterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.getNext() + " ");
        }The keword "this" is still a problem for me. I start to belive im stupid or something.
    Can you please explain what it does here? why not just write
    InnerEvenIterator iterator = new InnerEvenIterator();Regards / Magnus

    In the context of the example, this. is optional, but the authors were trying to emphasize that it's not simply a matter of creating an instance of any old class, so they explicitly used the this reference. The class reference is not always optional. If the printEven() method were defined as static, there would already have to be an instance of DataStructure such as ds created before the inner class could be instantiated:DataStructure ds = new DataStructure();
    InnerEvenIterator iterator = ds.new InnerEvenIterator();

  • How to declared an array of inner class ?

    can we declare array of inner class ?

    for example:
    Country.City.Airport.Flight[] fly = Country.City.Airport.Flight[VALUE];
    fly[0] = ( ( (new Country()).new City()).new Airport() ).new Flight();
    System.out.println(fly[0].toString());
    Class Country {
    Class City{
    Class Airport{
    Class Flight{
    }

  • Pass an array of argument defined anonymous inner class

    Can someone plz tell me what is wrong with this code?How can I correct it?
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[5]{
                   public void disp(){
                        System.out.println("Array of inner classes disp");
    }     

    This is what I wanted to do:
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
              ni[1].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[]{
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside first implementor of NotImplemented interface");
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside second implementor of NotImplemented interface");
    Thanks for all your help...

  • Swing - how to pass selected value out from actionPerformed() inner class?

    Hi all,
    I have a form with JcomboBox and textfields and I have to update the database
    with the submitted values. How can I pass the comboBox value out? I cannot defined boxValue as final outside the inner class.
    JComboBox list1 = new JComboBox (vector1);
    list1.addActionListener ( new ActionListener() {
    public void actionPerformed (ActionEvent ev) {
    boxValue = (String) ((JComboBox) ev.getSource()).getSelectedItem();
    thanks
    andrew

    OK, OK, my bad for not reading the whole post...
    1. Who needs to know the current JComboBox value? If the code that needs to know has access to the JComboBox, it can just get it from there. If the code is invoking the form, it is the responsibility of the form, not the listener, to return the values to the invoker.
    Please give us more information about what you are tryiug to do.

Maybe you are looking for