user983246
user983246

Reputation: 1449

java frame and label

I wrote my program but I'm not getting why its possible to possible to write

frame.getContentPane().add(label);

I'm confused on the order of methods for the above code that corresponds with the full code below.

Is the add method calling the label object then calling getContentPane method to the frame object. Anyone can enlighten me regarding this concept. It would help a great deal if I can fully understand java much better. :)

JFrame frame = new JFrame ("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set the label
JLabel label = new JLabel("Hello world");
frame.getContentPane().add(label);

frame.setVisible(true);

Upvotes: 1

Views: 3212

Answers (2)

Dave Newton
Dave Newton

Reputation: 160181

You don't "call an object", you call an object's instance methods (in this case). The add() method is a method of the frame's content pane, that (in this case) takes a JLabel parameter.

  1. Call frame's getContentPane() method, then...
  2. ...call that object's add() method, passing...
  3. ...the previously-constructed JLabel instance (the label variable)

Just read from left-to-right.

Upvotes: 4

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

frame.getContentPane() returns a Container that the JFrame holds (actually a JPanel) that acts as its contentPane. Then the add(...) method adds the JLabel to the contentPane. The order is left to right.

This is equivalent:

JFrame frame = new JFrame ("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Hello world");
Container contentPane = frame.getContentPane();
contentPane.add(label);

Upvotes: 3

Related Questions