Hello, let's say I have these classes:

public class ClassA extends JFrame{

  private JButton btn1;
  private JPanel panel;

  public JPanel getPanel(){
      return this.panel;


    panel=new JPanel(new FlowLayout());
    btn1=new JButton("LALALA");



public class ClassB {
    ClassA a;

    ClassB(ClassA a){
       this.a = a;
       JButton button2 = new JButton("leButton");

       a.getpanel().add( button2 );



I guess it doesn't make much sense to declare + initialize a component in a class and then add it to another class extending a JFrame. What would happen if the object where the component is initialized were destroyed ?

Presuming you understand my question, what can I do and how? should I just add the button from classA, hide it and then make it visible from class B when I need to?


5 Years
Discussion Span
Last Post by mKorbel

As a general rule of OO design, you shouldn't have one class getting involved with the internals of another. It entangles them to the point where you dare not change one for fear of breaking the other - exactly the opposite of how it should be.
Without details of your exact requirement, I would say identify what adding the button is for, in architecture terms, and create a public method in class A to do that eg: if it's there to allow the user to Save under some circumstances you would have public void setSaveEnabled(boolean enable){ make button visible/invisible} Then in class B you can call that without knowing anything about what GUI controls class has or how it organises them. That's "encapsulation" the way it should be.

ps: You asked about object destruction - this happens as part of garbage collection in Java. As long as an instance of either class has a reference, direct or indirect, to the object it will not be garbage collected. It's a kind of "don't worry about it, it just works" thing. My objections to doing what you described are not that it won't work, because it will. It's just anti-encapsulation.


about object destruction

but there are some rules about GC, GC'ed are Object that is able to finalize(), for example that not possible with TopLayoutContainers, just dispose();

Edited by mKorbel: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.