Swing Component - disabling resize in layout

2019-06-28 01:38发布

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

3条回答
男人必须洒脱
2楼-- · 2019-06-28 01:44
//this will restrict size on fix size, what ever size you will define for panel like
//panel.setSize(400,400);


    panel.setMaximumSize(panel.getSize());
    panel..setMinimumSize(panel.getSize());
查看更多
来,给爷笑一个
3楼-- · 2019-06-28 01:45

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.

查看更多
可以哭但决不认输i
4楼-- · 2019-06-28 01:49

if you are using custom layout manager, change your current layout to GridBagLayout and change fill options to NONE, after that change it back to your first layout.

查看更多
登录 后发表回答