Search code examples
javaswingextendjcomponent

What's the rule of thumb regarding Swing component extension?


When dedicating a class to a particular Swing component, is it better to extend that particular component, or construct it internally and provide a reference?

public class Foo extends JComponent{

}

OR

public class Foo{
    public JComponent getComponent(){
    }
}

EDIT

This is what I mean by dedicating

public class Foo{
    private static Foo INSTANCE;

    public static Foo getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Foo();
        }
    }

    public void createAndShowComponent(){
        //do stuff
    }
}

Inside createAndShowComponent(), I create a JComponent with all its components and their respective listeners without exposing the internals of the component I just created.


Solution

  • +1 for Composition over extension. It makes the API much cleaner since you only expose what methods are important for your new component