Why aren't these statements equivalent?

B

burrise

Can someone explain why statements A and B below are not equivalent?
When you compile and run the program the first button is at its
preferred size and the second is resized to fill the grid cell. It's as
if the second button is added without the JPanel around it. I'm really
confused. They look like equivalent ways of doing the same thing.

Eddie

import java.awt.*;
import javax.swing.*;

public class test extends JFrame {
public test() {
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(1,2));

/* A */ JPanel tempPanel = new JPanel();
tempPanel. add(new JButton("First"));
add(tempPanel);

/* B */ add((new JPanel()).add(new JButton("Second")));
}

public static void main(String[] args) {
JFrame frame = new test();
frame.pack();
frame.setVisible(true);
}
}
 
C

Chris Smith

Can someone explain why statements A and B below are not equivalent?
When you compile and run the program the first button is at its
preferred size and the second is resized to fill the grid cell. It's as
if the second button is added without the JPanel around it.

Yes, that's exactly what happens. Read the API docs for the
Container.add(Component) method. They say:

Returns:
the component argument

In other words, the result of (new JPanel()).add(new JButton("...")) is
not the JPanel, but is rather the JButton. When the JButton is added to
the content pane, it is removed from the JPanel that you just added it
to.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
K

klynn47

I think the problem is that the return type of add in Component is
Component, and you get back the component that you add. In statement B,
the output of the add method you call is the button and not the JPanel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top