Design question on inner class

I have an app, with a JPanel. The way I have it setup right now is the JPanel is an inner class with an overloaded constructor. I call the inner class depending on the arguements. this is done repeatedly in my program.
My question is: Should I be doing it this way or maybe as a method that returns the updated JPanel? Can this cause serious memory problems?
example
private void CreateTextfields(int q, int c){
// c =      number of choices selected from other JComboBox
// q =      question selected from combo box
// questions is the arrylist containing all questions
   AnswerPanel answerPanel;
   answerPanel = null;
   textFieldPanel.removeAll();
if( questions.isEmpty() && c > 0 ){
         answerPanel = new AnswerPanel(c);
else if( !questions.isEmpty() && c == 0 ){
         answerPanel = new AnswerPanel(q, listOfAnswers);
else if( !questions.isEmpty() && c > 0 ){
         clearLogic();
         answerPanel = new AnswerPanel(q, listOfAnswers, c);
         textFieldPanel.add( answerPanel, BorderLayout.CENTER ); Thanks
Jim

<<serious memory problems>>
Probably not. But it seems wasteful to keep creating a new object just to set some properties. Why not make a single AnswerPanel, with overloaded setContents() functions?
Not that I'm a Swing expert or anything....
HTH,
Ken

Similar Messages

  • Question on inner classes

    I have a class that has 3 inner classes, on class read the colors and font settings, how can I pass this class to the 2 other inner classes
    Here is a watered down version of code:
    class MainClass{
           public MainClass(){
                 // do some stuff
                 innerClass3  ic = new innerClass3();// I need to pass this to the other inner classes
                 layeredPane.add( new innerClass1( some Variable), 1);
                 layeredPane.add( new innerClass2( anotherVariable), 2 );
    class innerClass1 extends JTextPane{
         public innerClass1( String s ){
    // instead of doing this
              innerClass3 ic = new innerClass3();
              setBackground(ic.getBackground() );
    class innerClass2 extends JPanel{
            public innerClass2( String[] z){
             // and this again
                innerClass3 ic = new innerClass3();
                setForeground(ic.getFontClor());
    class innerClass3{
    Color background;
    Color foreground;
        public innerClass(){
         setColors();
    public void setColors(){
       background = Color.blue;
       foreground = Color.red;
    public Color getBackground(){
       return background;
    public Color getFontColor(){
    return foreground;
          

    Thanks for the reply
    Works well for first screen, but I recall the innerClasses(1 and 2) from an actionPerformed in innerClass2 and I keep getting nullPointerError when referring to innerClass3. Each screen will have different fonts and colors, so I need it to update after each button click.
    // this is inside innerClass2( it's panel with buttons )
    // the next screens graphics will depend on which button is selected
    public void mouseReleased(final java.awt.event.MouseEvent e) {
             layeredPane.removeAll();
              currentQuestionNumber++; 
              question = questionText[currentQuestionNumber] ;  
    // adds a JTextPane with question         
              layeredPane.add(new innerClass1(question, ic), 1 );
    // adds a JPanel with buttons
              layeredPane.add(new innerClass2( currentQuestionNumber, ic ), 3 );Will be tearing hair out soon
    Jim

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • Inner Classes - when to use with Swing?

    Hi again,
    I was creating a GUI with JTabbedPane as content pane, while doing the single panes in the different tabs i started wondering about some design issues.
    Let�s say you have a pane that is composed of 3 "subpanes" ( containing all the interaction components ). Should i write "normal" classes for each of the subpanes or is it more reasonable to define them as inner classes of the "main" panel - that�s at least what i thought because those 3 smaller panels are bound to the main panel for their lifetime...
    Any design tips about inner classes and swing or even inner classes in general, i�d really appreciate.
    Thx

    The concept of inner classes design in java is (I hope) they provide 'composite aggregation' relation with the contained class.
    Means that the (inner) class cannot exists alone and provide functionalities like other classes. Inner classes refer to the "contains" relationship in the UML.
    The other regular associations say, having a value oject model to an UI are Structural Aggregation, means that the value object can be used in the UI and also separately.
    For your case the inner classes are not suitable. You may have to find a suitable mechanism to get the individual tab panes. Probably use an interface to bridge the three tab panes and use an manager class, pass and id to the manager class and get the required Tabbed pane.
    Thanks,
    ananth
    Hi again,
    I was creating a GUI with JTabbedPane as content pane,
    while doing the single panes in the different tabs i
    started wondering about some design issues.
    Let�s say you have a pane that is composed of 3
    "subpanes" ( containing all the interaction components
    ). Should i write "normal" classes for each of the
    subpanes or is it more reasonable to define them as
    inner classes of the "main" panel - that�s at least
    what i thought because those 3 smaller panels are
    bound to the main panel for their lifetime...
    Any design tips about inner classes and swing or even
    inner classes in general, i�d really appreciate.
    Thx

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

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

  • Question about Inner/Outer classes

    Hello!
    I'm still preparing for java cert exam and have a question. If I have Outer and Inner classes like this:
    Outer o = new Outer();
    Outer.Inner i = o.new Inner();Does this mean that 'i' has a reference to both Outer and Inner classes. Moreover, does 'i' have a reference to the 'this' of 'o'?
    Thanks,
    Victor.

    "i" doesn't have a reference. "i" is a reference. I think you are trying to express this:
    import java.lang.reflect.*;
    public class Outer {
        class Inner {
            private int foo;
        public static void main(String[] args) {
            Outer o = new Outer();
            Outer.Inner i = o.new Inner();
            for(Field field : i.getClass().getDeclaredFields()) {
                System.out.format("%s %s %s;%n", Modifier.toString(field.getModifiers()),
                    ((Class)field.getGenericType()).getName(), field.getName());
    }

  • I don't understand the design of inner class private member

    This is a question about the java language specification of inner classes.
    In the java langage specification document, we read
    If the member or constructor is declared private,
    then access is permitted if and only if it occurs
    within the body of the top level class (�7.6)
    that encloses the declaration of the member.
    This allows following code :
      public class PrivateTest {
        public PrivateTest()
          Hello hello = new Hello();
          System.out.println(hello.secret);
        class Hello
           private String secret = "This is a secret";
      } wherein accessing the private secret field is allowed
    from into the PrivateTest enclosing class.
    My questions are :
    a) It seems that private methods or constructors of
    inner classes have no meaning, we could also declare
    them as public. True or false ?
    b) Is there any reason that Java bypass this private
    mechanism ?
    c) Why is the above definition not written with
    "first enclosing" instead of "top level" ?
    Thanks in advance

    Private methods and constructors of an inner class can only be accessed within the outer class. Other classes can't instantiate it or use the private methods.
    You can also make your inner class private, so it is not possible to refer to the class from outside (and thereby another way of preventing it from being instantiated).
    So it does matter which access modifiers you use.
    I think top level is more precise than first enclosing, because you can have inner classes in inner classes, which are still available for the top level class (haven't tested this).

  • Program Design Problem: Inner Class use verse interacting seperate classes?

    i am designing a GUI based program that needs to have 2+ windows that interact with each other. In my original design there were just two windows: the World display, and the tile choser (this is for 2D map editing). Because there were only 2, I made them both inner classes of another class. The top level class's fields were how I got the two windows to interact.
    Now I am adding more tile choser esque windows and it is getting very confusing and the amount of Fields is getting ridiculous and the whole thing isnt very OO.
    I thought about splitting up the World Display window and the Tile Choser window into two different classes and just have multiple instances of the Tile Choser class for the additional windows.
    The problem is the interaction. I could pass all of the variables that both classes require to constructers and set up lots and lots of get and set methods, but then that seems to destroy the whole idea of two classes. The whole project is getting really messy.
    Any thoughts?
    I know that was a jarbled explanation so just ask about any part that might be unclear

    Create an object that represents the state being manipulated. The model.
    Create methods to modify that data. Not getters/setters, but controllers. If it's a map, then maybe a method would be "addTown" or something. This represents the controller.
    Create methods to render the data graphically. The views.
    Pass this object to GUI widgets, or reference it from inner event handlers.

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

  • Inner classes - a general question

    i'm having some difficulties understanding when to use a static inner class
    and when to use a non static inner class
    lets say i'm implementing a LinkedList , and i want my nodes and my iterator
    implemented in inner classes .
    when and why should i declare them static or non static.
    thank you very much in advance.

    Inner classes are never static. Nested classes can be either static or non-static; a non-static nested class is called an inner class.
    Anyway, an inner class implicitly gets a reference to an object of the outer class, while a static nested class doesn't, so the decision should depend on whether or not it needs that.
    An iterator would need a reference to its collection so it would be a non-static nested class. A node wouldn't so it would be a static nested class.

  • A question about local inner classes

    Suppose an inner class created in a method:
    public void thisMethod(final int a){
                 class InnerClass {
                   //code
    }Why, in order to use the parameter a in the inner class, I have to pass it final?

    Aurelious wrote:
    JoachimSauer wrote:
    Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
    Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
    On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
    So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

Maybe you are looking for

  • Removing quotation marks from channel names

    Firstly - I am new to both DIAdem and VB so please forgive my ignorance! I have a large data set containg many groups with (almost) identical channel names in each group. For reasons not worth going into some of the channel names have quoation marks

  • Hierarchy Objects - Authorisation in Roles

    Hi I have created a role which is causing me few problems. The role is reporting role and the queries associated to it have 0MAST_CCTR & 0ORGUNIT in them. when I run the queries I got a error message: No authority for the node from characteristic 0MA

  • EXEC SQL PERFORMING

    when run the following program ,it reported error as "the error occurred in the current  database connection "DEFAULT". how to solve the problem ? ================================= DATA : BEGIN OF WA,   CLIENT(3),   ARG1(3),   ARG2(3),   END OF WA. D

  • Low image quality on Android using CameraRoll.addBitmapData

    When using CameraRoll.addBitmapData on Android the resulting .jpg's quality is quite low in what looks like 50% jpg compression. In iOS the quality is much better. How do I reduce the compression on Android and increase the image quality? I don't qui

  • A Collection of Integer(s) and Must Sort By intValue()

    My code is to go through a loop. In each loop, several primitive int values will be found. And I have save all those primitive int values. After the looping process, I have to sort this collection of int values. My question is what kind of List shoul