views:

44

answers:

2

I have the following structure:

public class A {
     private javax.swing.JLabel fullName;

     public class B {
             public B() {
                    fullName.setText("Martha Stewart");
             }
     }
     ...
     ...
     ...
}

My goal is to have B (currently the sub class of A) to be in a separate class.

The problem is: When I separate the two classes, I lose functionality on the .setText() call for the JLabel. I realize that if B is in a separate class, I would have to write a public setter method in class A.

This, however, is not plausible since I have about 100 buttons and use 4-5 different functions for each button. Creating a getter/setter method for each function is not plausible IMHO.

I'm trying to wrap my head around a better solution... can any of you help, friends?

+2  A: 

B isn't a subclass of A. It's a nested (inner) class within A.

However, you shouldn't try to get access to fields of other types - it breaks encapsulation. Properties are a nicer solution - or alternatively, a setFullNameText method which calls fullName.setText() itself. Just because you have 100 buttons (ouch!) doesn't mean it's time to throw encapsulation out of the window. It does mean you might want to consider grouping those 100 fields into smaller classes though...

Jon Skeet
Thanks for the response! Is there a way to autogenerate getter/setters or must I individually do it one by one?
Carlo del Mundo
An IDE like Eclipse can generate all of them.
Samuel_xL
+2  A: 

Don't let a class modify the attribute of another class, this breaks encapsulation. If you can't stand getters and setters, I'd suggest a configuration object (like a map), which could be given to the constructor and/or a setter of your main GUI class.

By the way:

I have about 100 buttons

I think it's a main issue. You should break your GUI in several classes representing groups of controls.

Samuel_xL