2

This seems like a very beginner question, but I don't know the answer.

Suppose you create a new JFrame in Java. With the new frame comes the default content pane. If I declare a variable and initialize it as that frame's content pane, is the variable I initialized a reference to the frame's content pane or does it become its own thing? Example:

JFrame frame = new JFrame();
Container panel = frame.getContentPane();

If I wanted to, for example, change the layout of the content pane, would adjusting panel give the same effect as changing frame.getContentPane()?

To show exactly what I mean:

frame.getContentPane().setLayout(new GridLayout());

Would this create the same result as:

panel.setLayout(new GridLayout());

Will anything that I then do to panel then be reflected in frame without me having to then say frame.setContentPane(panel); at the end?

charlieshades
  • 323
  • 1
  • 3
  • 16
  • "As a convenience `add` and its variants…have been overridden to forward to the `contentPane` as necessary."—[`JFrame`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html) – trashgod Jul 18 '12 at 02:05

4 Answers4

1

Yes. An object in the memory can have multiple references, and any change on any of them will be reflected on all of them (since they all are pointing to the same object). See this example for more details.

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

Absolutely. They point to the same object in memory.

Imagine tying two strings to a balloon. You hold one (let's call you panel) and you give the other string to a friend (let's call him frame.getContentPane()).

Now if you your friend follows his string, finds the balloon, and puts a hat on it (i.e. frame.getContentPane().setLayout(new GridLayout());), then when you follow your string, you will find a balloon with a hat!

cklab
  • 3,761
  • 20
  • 29
0

Yes they refer to the same Container object.

In other words, getContentPane() returns a reference to the underlying Container. Thus whenever you use the reference, the underlying object is used/affected.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
0

Your code

JFrame frame = new JFrame();
Container panel = frame.getContentPane();

indeed lets the variable panel point to the content pane of the frame. So calling

panel.setLayout( new GridLayout() );

will affect the layout of the content pane, as panel refers to it.

However, a common mistake is to assume that if you do something like

JFrame frame = new JFrame();
Container panel = frame.getContentPane();
//... some more code

JPanel someOtherFancyPanel = ...;
panel = someOtherFancyPanel;

that the content pane of the JFrame would become someOtherFancyPanel. This is of course not the case. The last statement just let the panel variable point to someOtherFancyPanel and no longer to the content pane of the frame, and leaves the content pane un-altered.

Robin
  • 36,233
  • 5
  • 47
  • 99