Austin Hyde
Austin Hyde

Reputation: 27436

Java class initialization conundrum

I am using NetBeans' GUI Designer to create some JDialogs, which I then subclass from my own EditorDialog class.

Before I go further, consider this sample code:

class MyDialog extends EditorDialog {
    private Color someVariableThatTheGuiNeeds = new Color(0,50,100);

    public MyDialog() {
        super(true);
    }

    //<auto-generated>
    private void initComponents() { //note this is private!
        //...
    }
    //</auto-generated>
}

abstract class EditorDialog extends JDialog {
    public EditorDialog() {
        super(null,true);
    }
    public EditorDialog(boolean stuffNeedsDone) {
        super(null,true);
        //initComponents();
        doStuffAfterGuiInitialized();
    }
}

The problem is, I can't call initComponents() from my superclass, because it is private.

To get around this, I tried a workaround to the classes:

//in EditorDialog
public EditorDialog(boolean stuffNeedsDone) {
    super(null,true);
    workaround();
    doStuffAfterGuiInitialized();
}
protected abstract void workaround();

//in MyDialog
@Override
protected void workaround() {
    initComponents();
}

And, of course, this doesn't work, because someVariableThatTheGuiNeeds isn't initialized when initComponents() gets called because of the way the initializations happen:

Also, I cannot create a non-private abstract initComponents() in EditorDialog, because the visibility when overriding can only become more public.

So, how can I get around this problem, without making it too hackish?

(If you are unfamiliar with NetBeans, I cannot edit auto-generated code, and there is no option (that I could find) to change access modifiers on the initComponents() method.

Upvotes: 1

Views: 292

Answers (2)

KLE
KLE

Reputation: 24159

This is a problem that is common in java. Instanciation is not a friend of subclassing.

An indirect solution is used by many : call an init() method once the object is fully build.

This is often automated via a factory. All injection frameworks (like Spring) do this routinely.

Upvotes: 0

akf
akf

Reputation: 39485

Your constructors shouldn't call non-private methods in any case. If you require initialization for your dialogs after they are created, you can create an init() method that should be called after the constructor is finished.

Note, the method name doStuffAfterGuiInitialized() indicates a bit of a misunderstanding. The GUI, or even the instance, isnt fully initialized until after the constructor completes.

Upvotes: 1

Related Questions