Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing Component - disabling resize in layout

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

like image 798
Michael Avatar asked Jun 27 '11 12:06

Michael


People also ask

How do I stop JPanel from resizing?

Making a Frame Non-Resizable: use setResizable(false) to freeze a frame's size. : JFrame Window « Swing « Java Tutorial. 14.80.

Which method is used for resizing the frame in Java?

To resize a frame, There is a method JFrame. setSize(int width, int height) which takes two parameters width and height. Below is the code to change the window size of a JFrame.

What method is used to prevent a user from changing the size of a frame () object *?

The setBounds() method is used in such a situation to set the position and size. To specify the position and size of the components manually, the layout manager of the frame can be null.

Which layout manager gives the minimum size to a component?

Many layout managers do not pay attention to a component's requested maximum size. However, BoxLayout and SpringLayout do. Furthermore, GroupLayout provides the ability to set the minimum, preferred or maximum size explicitly, without touching the component.


1 Answers

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.

like image 166
aioobe Avatar answered Nov 04 '22 02:11

aioobe