Question

Same thing in two ways. What is different in these lines?

in 1st Statement getContentPane() Method is used ,What is the Purpose of it? is this Shorthand of 2nd Statements

JLabel lblNewLabel = new JLabel("New label");
getContentPane().add(lblNewLabel, BorderLayout.NORTH);

in this An Object Declared contentPane and after set the Layout and then set the value of setContentPane by passing and then add without using getContentPane()

contentPane = new JPanel();             
 contentPane.setLayout(new BorderLayout(0, 0));
 setContentPane(contentPane);

 JLabel lblNewLabel = new JLabel("Name");
 contentPane.add(lblNewLabel, BorderLayout.NORTH);

Plz help me .these lines confusing me.

Was it helpful?

Solution

There's little difference between the two. The first example simply uses the default content pane create by the parent window, where by the second creates its own content pane and uses the reference directly.

You could also use...

Container contentPane = getContentPane();

JLabel lblNewLabel = new JLabel("Name");
contentPane.add(lblNewLabel, BorderLayout.NORTH);

Take a look at How to use Root Panes for more details

I should highlight the fact that, by default, JFrame's content pane uses a BorderLiayout, meaning you first example doesn't need to set the layout, but JPanel uses FlowLayout, so it changed the layout manager to confirm to the expections of a JFrame...I guess ;)

OTHER TIPS

simply create a panel and add your components to that panel at the end of code

write this one

getContentPane().add(yourPanel);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top