2

I've seen a couple of ways of doing theism they both seem to work but I'm just wondering if one is better practice over the other.

For example, with a JFrame called myFrame you could do:

myFrame.add(new JButton("OK"));

And you can also do:

Container c = myFrame.getContentPane();
c.add(new JButton("OK"));

Is one of these 'correct'?

3 Answers 3

7

A literal copy from the class javadoc of JFrame

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write:

   frame.add(child);

And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame.

So both are equivalent, and both are correct

Sign up to request clarification or add additional context in comments.

Comments

2

From Java5 isn't required

  • to add JComponents to the ContentPane, just JFrame.add(JComponent)

  • JFrame has implemented BorderLayout, then myFrame.add(new JButton("OK")); is placed to the CENTER area

Comments

1

I would definetly say that the

Container c = myFrame.getContentPane();
c.add(new JButton("OK"));

Is the most practical one. Since you will most likely later on need to use the container that is the

myFrame.getContentPane();

you don't need to write it again later. It will for example be used if you need to set another layout for the frame. But as said earlier, both can be used.

1 Comment

each and every unnecessary letter is noise and noise leads to unmaintainable code :-) While there are properties of the contentPane that are accessible only directly (like f.i. background, opaque ..), layout is not one of those so your argument is .. cough ...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.