user1415043
user1415043

Reputation: 7

Fixed size of panel in frame

I have added some components to JPanel which is set to grid layout, and I'm adding this to JFrame which is set to border layout. But I want to fix the size of the panel. When my window is maximized, the size of all components are increasing. I want the panel at the center of the window, with fixed size even if window is maximised.

Upvotes: 0

Views: 10232

Answers (3)

Liu guanghua
Liu guanghua

Reputation: 991

    JFrame frame = new JFrame();
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());

    JPanel rootPanel = new JPanel();
    frame.getContentPane().add(rootPanel, BorderLayout.CENTER);
    rootPanel.setLayout(new GridBagLayout());

    JPanel contentPanel = new JPanel();

    Dimension dimension = new Dimension(300, 300);
    contentPanel.setMaximumSize(dimension);
    contentPanel.setMinimumSize(dimension);
    contentPanel.setPreferredSize(dimension);
    contentPanel.setBackground(Color.YELLOW);

    GridBagConstraints g = new GridBagConstraints();
    g.gridx = 0;
    g.gridy = 0;
    g.anchor = GridBagConstraints.CENTER;
    rootPanel.add(contentPanel, g);

    frame.setVisible(true);

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168825

Put the panel with GridLayout as a single component to a GridBagLayout with no constraint - it will be centered. Add the panel with GBL to the CENTER of the BorderLayout.

See this example for the above image.


The Nested Layout Example also uses GBL to center the image in the lower part of the scroll-pane on the right.

Upvotes: 3

brimborium
brimborium

Reputation: 9512

Well then you should not use BorderLayout, because that just fits the child components in. If you still want to use BoderLayout on the JFrame (because you need some side panel or something like that), You can just wrap your JPanel (with the GridLayout) into another JPanel with a GridBagLayout or BoxLayout or something similar and then put that other JPanel into the JFrame.

JPanel innerPanel = new JPanel();
innerPanel.setLayout(new GridLayout());
// fill and set your innerPanel

JPanel middlePanel = new JPanel();
middlePanel.setLayout(new GridBagLayout());
middlePanel.add(innerPanel, constraintsThatPlaceItWhereYouWantIt);

JFrame yourFrame = new JFrame();
yourFrame.setLayout(new BorderLayout());
yourFrame.add(middlePanel, BorderLayout.CENTER);

Upvotes: 1

Related Questions