Swing组件 - 禁用布局中的调整大小

Mic*_*ael 5 java layout user-interface swing resize

我有一个自定义GUI compomemt,它基于Swing的JPanel.此组件放置在使用BorderLayout的JFrame中.当我调整框架大小时,此组件会继续调整大小.我怎么能避免这个?无论发生什么,我都希望组件保持相同的大小.我已经尝试过setSize,setPreferredSize,setMinimumSize但没有成功.

提前致谢!

中号

aio*_*obe 6

你有几个选择:

  • 将组件嵌套在内部面板中LayoutManager,但不会调整组件的大小

  • 使用比更复杂的LayoutManager BorderLayout.在我看来,这样GridBagLayout会更好地满足您的需求.

第一个解决方案的示例:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

放置绿色组件BorderLayout.CENTER,红色组件保持首选大小.