Reputation: 1449
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
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.
frame
's getContentPane()
method, then...add()
method, passing...JLabel
instance (the label
variable)Just read from left-to-right.
Upvotes: 4
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