Free space between components and border of containter in FlowLayout

1.1k views Asked by At

When I put something in content pane that has flow layout manager i get free space between that component and borders of content pane.

The default flow layout has hgap and wgap non-zero, but setting them to zero DOESN'T solve the problem.

NOTE: Please help me in this layout, and not suggest to use another layout, cause this is excerpt from larger app.

Setting negative hgap and wgap can help but this is surely not the solution. Here is the code to inspect:

import java.awt.*;
import javax.swing.*;

public class MainWindow extends JFrame{

public MainWindow (){
    JPanel contentPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));

    JPanel wp = new JPanel();
    wp.setPreferredSize(new Dimension(500, 500));
    wp.setBackground(Color.DARK_GRAY);

    contentPane.add(wp);

    setContentPane(contentPane);

    pack();
    setResizable(false);
    setVisible(true);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
        new MainWindow();
}
}
1

There are 1 answers

6
croraf On

I found the answer on another topic. You must write setResizable(false) BEFORE calling pack(). Haven't found the explanation why is this necessary, I assume that it's because pack() is adding some extra space for the frame. How to solve this if you don't want to make the window resizable I don't know. NOTE: You have the same problem with other LayoutManagers such as BorderLayout (the manager with pack adds extra space).