I created a JFrame with BorderLayout and one Panel on the east (blue) and one in the center(green. The center panel contains an orange panel which will always stay a square.
I just cant figure out why the organge panel always has a gap at the top (also after resizing) because I did not set any gaps at all. This is how it looks and this is what I tried:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(600+200, 600));
frame.setLocationByPlatform(true);
BorderLayout borderLayout = new BorderLayout();
frame.setLayout(borderLayout);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
rightPanel.setPreferredSize(new Dimension(200, 600));
frame.add(rightPanel, BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.GREEN);
SquarePanel squarePanel = new SquarePanel();
squarePanel.setBackground(Color.ORANGE);
centerPanel.add(squarePanel);
frame.add(centerPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
}
public class SquarePanel extends JPanel {
@Override
public Dimension getPreferredSize() {
Dimension d;
Container c = getParent();
if (c != null) {
d = c.getSize();
} else {
return new Dimension(10, 10);
}
int w = (int) d.getWidth();
int h = (int) d.getHeight();
int s = (w < h ? w : h);
if(s%8 != 0){ // make Dimensions stay multiples of 8
s = s - s%8;
}
return new Dimension(s, s);
}
}
Unfortunately, boarderLayout.setVGap(0) does not work.