1

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

enter image description here

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

Ferryzijl
  • 642
  • 2
  • 8
  • 22

3 Answers3

1

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.

  • See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) Long story shortened. In this case it is better to override the `getPreferredSize` method, than call `setPreferredSize` .. But +1 for being the only answer that was headed in the right direction. – Andrew Thompson Jan 21 '16 at 00:53
0

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

  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) And that should have been a comment in any case. – Andrew Thompson Jan 21 '16 at 00:51
-1

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)

YounesM
  • 2,279
  • 15
  • 28
  • it doesn't work, if you remove the black panel the right panel will fill the frame, if i add something to to the black frame it will place it in the centre – Ferryzijl Jan 20 '16 at 13:30