6

Rather basic question here guys.

Basically I have code like this:

public SuperPanel() {
    setLayout(new BorderLayout());
    add(panel1(), BorderLayout.NORTH);
    add(panel2(), BorderLayout.CENTER);
    add(panel3(), BorderLayout.SOUTH);
}

And that all works well and good. The problem is that I have another part I wish to add to the center. Just using add(newPanel(), BorderLayout.CENTER) doesn't work, obviously. But you can add JPanels in JPanels, correct?

So I made the following change:

public SuperPanel() {
    setLayout(new BorderLayout());
    add(panel1(), BorderLayout.NORTH);
    add(supersweetpanel(), BorderLayout.CENTER);
    add(panel3(), BorderLayout.SOUTH);
}

With supersweetpanel() being:

public JPanel supersweetpanel() {
    JPanel sswp = new JPanel();
    setLayout(new BorderLayout());
    add(panel2(), BorderLayout.NORTH);
    return sswp;
}

Now it overrides panel1! If I set it to anything else (CENTER, SOUTH, what have you), the first two panels disappear entirely. Help is much appreciated.

1 Answer 1

14

SuperPanel is likely a subclass of JPanel, right? You are accidentally adding panel2 to this (the SuperPanel), not sswp. Try:

public JPanel supersweetpanel() {
        JPanel sswp = new JPanel();
        sswp.setLayout(new BorderLayout());
        sswp.add(panel2(), BorderLayout.NORTH);
        return sswp;
    }
3
  • 2
    +1. That's got to be it, and it gives a good example of why using inheritance can make things fragile.
    – Eddie
    Commented May 26, 2009 at 22:58
  • Ah, that was it exactly. Lovely.
    – Peter C.
    Commented May 26, 2009 at 23:12
  • What Eddie said. It's a shame most Swing tutorials (and Swing GUIs) have such bad code. Commented May 27, 2009 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.