Game Development: Construction Method (Java Design Pattern)

If you want to extend a Class and do some stuff, before the super constructor gets called, you can do the following:

Create static methods, which return everything your super constructor needs.
Here is a simple example from LibGDX. I wanted to extend ScrollPane and provide some additional predefined values.

What I wanted to do is:
  • children of my ScrollableWidget should always sit in the middle
  • both scrollbars should always be active
  • children should always sit in the middle of a bigger container (overscrolling)

public class ScrollableWidget extends ScrollPane {

    public ScrollableWidget( 

        int scrollWidth, int scrollHeight, 

        int childWidth, int childHeight, Actor child, Skin skin) {


        super(construct(childWidth, childHeight, child), skin);
        setSize(scrollWidth, scrollHeight);
        setScrollBarPositions(true, true);


    private static Actor construct( 

        int width, int height, Actor child) {


        Group container = new Group();
        child.setPosition(width/2-child.getWidth()/2,height/2-child.getHeight()/2, Align.bottomLeft);

        return container;

No comments:

Post a Comment