Adding inner class object

Hello to all
I have one doubt regarding eventhandling. Consider i am having one class named outer which extends applet and with in outer class i am having one class inner which extends panel.
Now when i try to add the inner class object in action performed of outer
class it doesnt get added. How to overcome this.
Eventhough sometimes it gets added it shouldnot appear for the first time. After resizing the window only it gets displayed.
How to over come this.
This is my coding
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet implements ActionListener{
     JButton b1;
     Container c;
     public void init()
          c=getContentPane();
          b1=new JButton("First");
          c.add(b1,BorderLayout.NORTH);
          b1.addActionListener(this);
     public void actionPerformed(ActionEvent ae)
          System.out.println("Working");
          c.add(new panel());
     class panel extends JPanel
          int a=5;
          JLabel l=new JLabel("ADSF");
          public panel()
               add(new JButton("ASDFASDFs"));
               add(l);
          /*public void paint(Graphics g)
               g.drawString("ASDFASDF123123123123",20,20);
}

You could try being more specific when you add ie
c.add(new panel(), BorderLayout.CENTER);

Similar Messages

  • Confused about creation of inner class object of a generic class

    Trying to compile to code below I get three different diagnostic messages using various compilers: javac 1.5, javac 1.6 and Eclipse compiler. (On Mac OS X).
    class A<T> {
        class Nested {}
    public class UsesA <P extends A<?>> {
        P pRef;
        A<?>.Nested  f() {
            return pRef.new Nested();  // warning/error here
    Javac 1.5 outputs "UsesA.java:11: warning: [unchecked] unchecked conversion" warning, which is quite understandable. Javac 1.6 outputs an error message "UsesA.java:11: cannot select from a type variable", which I don't really undestand, and finally the Eclipse compiler gives no warning or error message at all. My question is, which compiler is right? And what does the message "cannot select from a type variable" means? "pRef", in the above code, is of a bounded type; why is the creation of an inner object not allowed?
    Next, if I change the type of "pRef" to be A<?>, javac 1.6 accepts the code with no error or warning message, while javac 1.5 gives an error message "UsesA.java:11: incompatible types" (concerning the return from "f" above). Similarly to javac 1.6, the Eclipse compiler issues no error message. So, is there something that has changed about generics in Java between versions 5 and 6 of the language?
    Thanks very much for any help

    Checkings bugs.sun.com, it seems to be a bug:
    http://bugs.sun.com/view_bug.do?bug_id=6569404

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

  • Inner classes question

    Hi guys,
    I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
    Is it how it's done or am i doing something wrong?
    public class A
        // Some code here
        public class B
             //Some code here
    }Trying to create an instance:
    A a = new A();
    A.B b = a.new B();

    What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
    >
    There are two ways to create "inner" class object,
    1)The way you have written the codeTrue.
    2)
        public class A
    {    // Some code here    
    public void createInner()
    classB b=new ClassB();
    public classB   
    //Some code here   
    That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway?

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

  • Deployment problem: Inner class not included

    Hi, All:
    I am trying to deploy my Java application using JDeveloper 3.2. I was be able to successfully deployed it when I first designed the project, even some of the files also have inner classes. Now I have added some new inner classes to a public class and tried to re-deploy it. However how hard I tried (I have tried to rebuild the project, redefine the depoyment profile, even tried to add these class files directly through the advanced tab), the newly added inner class will not be able to be added to the deployed Jar file. I have checked the class files under myclass directory, and found all the inner class files are there, and I can run the application in JDeveloper without any problem. I wonder if there is any tricks to solve this problem. (Other than use the jar command).
    Thanks,
    Peter

    Also, it's probably a good idea to name your packages different than your classesMoreover, common naming conventions dictate you should never even use capitals in your package names if I'm not mistaken. Whereas class names should always at least begin with a capital.
    This will help prevent a lot of confusion, both for the developer and the IDE. ;-)

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

  • A question about non-static inner class...

    hello everybody. i have a question about the non-static inner class. following is a block of codes:
    i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
    but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
    is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
    does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
    thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
    // -------------- the codes -------------------
    import java.util.*;
    public class Inner0 {
    // definition of an inner class HaveValue...
    private class HaveValue {
    private int itsVal;
    public int getValue() {
    return itsVal;
    public HaveValue( int i ) {
    itsVal = i;
    // create an object of the inner class by calling this function ...
    public HaveValue getHandle( int i ) {
    return new HaveValue( i );
    public static void main( String[] args ) {
    Inner0 inn = new Inner0();
    Inner0.HaveValue hv = inn.getHandle( 100 );
    System.out.println( "i can create an inner class object." );
    System.out.println( "i can also get its value : " + hv.getValue() );
    return;
    // -------------- end of the codes --------------

    when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
    You can create an instance of the inner class as:
    outer.inner oi = new outer().new inner();

  • Doubt in Inner class

    hi ,
    i have a doubt. How we can access a Inner class name by the outer class name using the Dot(.) operator .
    For example if we want to refer to the Inner class in some other class
    then we must say "OuterClass.InnerClass".
    This type of syntex is ment for the static methods in a class.
    Thus can we assume that Inner class is also a type of static member.
    If not then please explain the syntex.
    i am also not getting the way we create object of the Inner class object in some other class . (i mean to say the logic behind the syntex)
    i.e
    OuterClass Ob1=new OuterClass();
    OuterClass.InnerClass InnOb=Ob1.new InnerClass();
    Cna any one please help me out.
    Regards
    Arunabh

    Hi,
    Inner classes are used to create some functionality in terms of OO way. Like you want to have event handling which will work only for designated GUI classes, then we can make use of Innner class.
    Within a outer classes we do not require any reference of outer object BUT, if you want to access Inner class object outside the class then only we need a reference of Outer object so that we instantitate Inner class object.
    thanks,
    Sandeep

  • Method local Inner classes

    The local variables of the method live on the stack, and exist only for the lifetime of the method. You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren’t guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them. Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class.
    Can any one explaing me with an example of the above BOLDED text.

    Can any one explaing me with an example of the above BOLDED text
    class Outer {
         Outer outer;
         void method() {
              int i=0;
              class Local extends Outer {
                   int j = i;
              outer = new Local();
    }The above code doesn't compile unless the i variable in method() is declared final.

  • Adding ItemListeners to an object created in an inner class?

    Hi All,
    I was wondering how dow you add ItemListeners to an object, thats created in an inner class of an outer class that implements the item listener interface. Or is it possible? I got around the problem by putting the createBox method in the outer class and calling it from the inner class, but it would be nice to know if you can keep it contained.
    i.e (Assume everythings declared, libs are imported, interface is implemented in outer class etc.)
    public class OuterClass implements ItemListener
        // Stuff
        class InnerClass
            // Yet more stuff
            void createBox (JPanel aPanel)
                 JCheckBox aBox = new JCheckBox;
                 aPanel.add(aBox)
                 // What should this line be ->
                 aBox.addItemListener(whatGoesHere?);
        // More Stuff
    }

    aBox.addItemListener(OuterClass.this);

  • 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

  • How to create an object of inner class

    hi i don't know how to create an object of an inner class..
    i got something like
    class Abc{
    private class Abcd {
    like this and i want to create an object of Abcd so that i can use some of method
    there..
    i think i should create the outter class object first right? but not sure
    the syntax.. i tried something like
    Abc.Abcd justTry = new Abc.Abcd()
    something like this..but not work..
    help me plz. ...

    If the nested class (that's not technically an inner
    class you have there) is not static, then you can't
    refer to it with OuterClassName.InnerClassName any
    more than you can refer to any other member--method
    or variable--with ClassName.staticMember.
    You need an instance.
    It's been a while since I've created an instance of a
    non-static nested class from outside that clsas, but
    I think it's something like this: Outer outer = new Outer();
    outer.Inner inner = new outer.Inner();
    Actually, I think it is this:
      Outer outer = new Outer();
      outer.Inner inner = outer.new Inner();Can't test it now though, gotta go to Taco John's for TACO TUESDAY!!!!
    Gotta love them crunchy shell bean tacos!!!

  • How to make an object of inner class and use it ?

    Hi tecs,
    In my JSF application i have a need to make an inner member class in one of my bean class.
    How can i make the object of this class?(what should be the entry in faces-config)
    And there are text box and check box (in the JSP) associated with the elements of this inner class. What should be the coding in JSP so that elements in the JSP can be linked with the corresponding members of the inner class ?
    Plz help.
    Thnx in advance.

    Hi
    I am havin 10 text boxes in my application.
    But out of 10 , 3 will be always together(existence of one is not possible without the other two.)
    Now i want to create a vector of objects ( here object will consist of the value corresponding to these three boxes),there can be many elements in this vector.
    So i m thinking to make an inner class which have three String variables corresponding to these text boxes that exists together.
    What can b done ?

  • Can I create the object of an protected inner class of a Base class in to t

    Dear All,
    Can I create the object of an protected inner class of a Base class in to the subclass ?
    e.g.
    public class Base{
         protected class Inner {};
    Public class Sub extends Base{
         Public Inner amethod (){
              Return new Inner(); //here I get an exception as
                                //Inner has protected access
    }Regards,
    Ishan

    @Op. The code that you posted isn't close to compiling. Java is case sensitive. It should be public and not Public, and return instead of Return.
    Kaj

Maybe you are looking for

  • HAP_Document BSP Application "Enter Objective Here "

    HI All BSP Expert and PMS Expert. BSP Standard application "HAP_DOCUMENT" Copy as a Z application. In Standard application "Enter Objective Here" Coming As Label but In Z Application i had changed as Input Field , That Input Field Values it  Does not

  • How to get Retro for a period or how to know which month is having retro

    Dear Freinds,            I would like to know how can i know which month is having Retro . Iam reading from the FM  cu_rgdir and further iam using PYXX_READ_PAYROLL_RESULT to get the payroll results. But when we see pc_payresult if we have for period

  • Change BgColors, FgColors for all Components in a Container?

    Is there a possibility to change the Background Color, the Foreground Color and the Fontsettings for all Components in a Container? Each Component in the Container should get the Colorsettings of the Container...

  • Relative Resizing issues

    Hi I started with java a few weeks back and I am really getting into using swing to make my problems. I've got the hang of GUIs for the most part but I've been having difficulty with the TextAreas and the sizing of panels 1) My TextArea problem: When

  • Manual removal of ZCM from SLES 64 bit...

    Is there a way to manually remove it? I tried the uninstall option and no go....