简体   繁体   中英

JFrame doesn't show the Jpanel's right

I'm using a JFrame with the size of 800x600. what i'm trying to do is make this:

在此处输入图片说明

the black Panel has 2 other panels inside of him with the size of 300x300 each.

the result is that the black panel is to the left (as suposed) and the red panel in in the centre with a gap on top between the frame and the panel. also, if i remove the black panel the right panel is filling the whole frame...

this is the code:

    //create the left part of the screen
    JPanel leftPanels = new JPanel();
    leftPanels.setLayout(new GridLayout(2,1));
    leftPanels.setSize(new Dimension(300,600));
    // just to illustrate the 2 panels inside of the black panel.
    //leftPanels.add(new JPanel());
    //leftPanels.add(new JPanel());

    //create the right part
    JPanel rightPanel = new JPanel();
    rightPanel.setSize(new Dimension(500,600));
    rightPanel.setBackground(Color.red);

    this.add(leftPanels);
    this.add(rightPanel);

    this.validate();
    this.repaint();

is there an easy way to fix this?

I also tried a Gridlayout on the JFrame but that gives me 2 panels of 400X600 each

First, use FlowLayout like this

setLayout(new FlowLayout(FlowLayout.LEFT));

Secondly, kindly use setPreferedSize rather than setSize for the JPanels

leftPanels.setPreferredSize(new Dimension(300,600));

I don't know what is cashRegister, but it looks like you are not adding the rightPanel to JFrame so make sure you add it.

Try to set the layout of the frame to null . Then use setBounds to position the panel.

If you are trying to set the panel relatively one from another set the frame layout to null

this.getContentPane().setLayout(null);

Then you will be able to place them absolutely. For more info : Doing Without a Layout Manager (Absolute Positioning)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM