saplingPro
saplingPro

Reputation: 21329

What difference does add method make over setContentPane?

This code,outputs a frame with a button placed over an image. If I change a statement from fr.setContentPane( new JPanel... to fr.add(new JPanel..., I only see the button with size of 700,700. What is the difference ?

public class Tester {

    public static void main(String args[]) {
        try {
            JFrame fr = new JFrame();
            fr.setContentPane(new JPanel() {
            BufferedImage image = ImageIO.read(new File("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\meaning.JPG"));
                @Override
                public void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   g.drawImage(image, 0,0,700,700, this);

                 }
            });
            fr.add(new JButton("Press Me"));
            fr.setSize(700,700);
            fr.setVisible(true);
            fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            fr.setResizable(false);
        }catch(Exception exc) {
            exc.printStackTrace();
        }
    }        
}

Upvotes: 1

Views: 1666

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

JFrame#add basically calls JFrame#getContentPane().add, so it's just shorthand.

So your code is actually saying...

fr.setContentPane(new JPanel() {...});
fr.getContentPane().add(new JButton("Press Me"));

Now, when you comment out the setContentPane line, JFrame uses a BorderLayout by default, the button is now being laid out in the CENTER position of the (frame's default) content pane and is filling the entire available space.

You could get the same effect as your original code by calling...

JPanel background = new JPanel() {...};
background.add(new JButton("Press Me"));
fr.add(background);

Take a look at Using top-level containers and How to use Root Panes for more details

Upvotes: 5

Related Questions