Đăng Nguyễn
Đăng Nguyễn

Reputation: 122

Set JPanel's size doesn't depend on JFrame 's size

My project have an JPanel and JFrame, (JPanel in JFrame). I set JFrame ' s size is (400,400). And the size of JPanel is (150,150). I add JPanel to JFrame and run it, when it displayed, the size of JPanel not is 150, it's size is same the size of JFrame. I don't know how to fix it :(

How to set JPanel's size doesn't depend on JFrame 's size?

Here my code:

public class Draw_JPanel extends JFrame{
Load_image panel_im = new Load_image();
public Draw_JPanel()
{       
    this.setSize(400,400);
    this.add(panel_im);
    }   
public static void main(String[] args){
    Draw_JPanel abc = new Draw_JPanel();

    abc.setVisible(true);
    }
}

and my Load_image class:

public class Load_image extends JPanel{
public Load_image()
{
    setSize(30,30);     
    this.setBackground(Color.RED);
}
}

Upvotes: 0

Views: 192

Answers (1)

alex2410
alex2410

Reputation: 10994

You add your panel directly to frame which has BorderLayout as default , it resizes your panel. Try to use this.getContentPane().add(panel_im); instead of this.add(panel_im); , because contentPane has flowLayout as default. Also read more about LayoutManager .tutorial.

Also use setPreferedSize() instead of setSize() (difference here)

Upvotes: 1

Related Questions