Swing Component - disabling resize in layout

17,377

You have a few options:

  • Nest the component in an inner panel with a LayoutManager that does not resize your component

  • Use a more sophisticated LayoutManager than BorderLayout. Seems to me like GridBagLayout would suit your needs better here.

Example of the first solution:

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

public class FrameTestBase extends JFrame {

    public static void main(String args[]) {
        FrameTestBase t = new FrameTestBase();

        JPanel mainPanel = new JPanel(new BorderLayout());

        // Create some component
        JLabel l = new JLabel("hello world");
        l.setOpaque(true);
        l.setBackground(Color.RED);

        JPanel extraPanel = new JPanel(new FlowLayout());
        l.setPreferredSize(new Dimension(100, 100));
        extraPanel.setBackground(Color.GREEN);

        // Instead of adding l to the mainPanel (BorderLayout),
        // add it to the extra panel
        extraPanel.add(l);

        // Now add the extra panel instead of l
        mainPanel.add(extraPanel, BorderLayout.CENTER);

        t.setContentPane(mainPanel);

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 200);
        t.setVisible(true);
    }
}

Result:

enter image description here

Green component placed in BorderLayout.CENTER, red component maintains preferred size.

Share:
17,377
Michael
Author by

Michael

Updated on June 04, 2022

Comments

  • Michael
    Michael almost 2 years

    I have a custom GUI compomemt, which is based on Swing's JPanel. This component is placed in a JFrame, that uses BorderLayout. When I resize the frame, this component keeps resizing. How can I avoid this? I would like the component to keep the same size whatever happens. I've tried setSize, setPreferredSize, setMinimumSize with no success.

    Thanks in advance!

    M

  • mre
    mre almost 13 years
    And I quote, "That won't work if the component in question is put in BorderLayout.CENTER for instance. The component will be resized regardless of those values." :)
  • mKorbel
    mKorbel almost 13 years
    yes as you said better would be look for another LayoutManager that's accepted Min/Max Size, really wrong example by usage of SetSize, please remove your adds code
  • aioobe
    aioobe almost 13 years
    @little bunny foo foo, no problem. For the record, 10k+ users can see deleted posts, so you could have put this comment below your own answer before deleting it.
  • Abdul
    Abdul almost 13 years
    oh i understand it now , i prefer don't use or add component directly to border layout centre but, try to create new JPanel with any other layout like flowlayout for now and add that component in the newly created flowlayout and add this newly created panel in to the center of the borderlayout panel, it will not resize the component inside the borderlayout panel.