繁体   English   中英

在BorderLayout.CENTER中设置JPanel的最大大小

[英]set maximum size of JPanel inside BorderLayout.CENTER

我在BorderLayout.CENTER中有一个JPanel

JPanel有一个网格布局,我希望它以CENTER的宽度扩展,但是高度必须停在最大值并尽可能使用preferredSize。

我有这个代码

JPanel wrapperCenterPanel = new JPanel(new FlowLayout());
wrapperCenterPanel.add(centerPanel);    
panel.add(wrapperCenterPanel, BorderLayout.CENTER);

centerPanel是我的面板(使用GridLayout),我用FlowLayout面板包装它,并将最后一个放在CENTER中。

现在尺寸是首选,但它是固定的! 如果需要,高度不会收缩,宽度也不会收缩。

我怎样才能做到这一点?

尝试使用BoxLayout作为包装器面板。 BoxLayout尊重组件的最大/最小和首选大小。

我认为BorderLayout不可能,特别是对于BorderLayout.CENTER区域,也没有side_effects,因为代码在屏幕上闪烁UFO

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class CustomComponent extends JFrame {

    private static final long serialVersionUID = 1L;

    public CustomComponent() {
        setTitle("Custom Component Graphics2D");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void display() {
        CustomComponents cc = new CustomComponents();
        cc.addComponentListener(new java.awt.event.ComponentAdapter() {

            @Override
            public void componentResized(ComponentEvent event) {
                setSize(Math.min(getPreferredSize().width, getWidth()),
                        Math.min(getPreferredSize().height, getHeight()));
            }
        });
        add(cc, BorderLayout.CENTER);

        CustomComponents cc1 = new CustomComponents();
        add(cc1, BorderLayout.EAST);

        pack();
        // enforces the minimum size of both frame and component
        setMinimumSize(getSize());
        //setMaximumSize(getMaximumSize());
        setVisible(true);

    }

    public static void main(String[] args) {
        CustomComponent main = new CustomComponent();
        main.display();
    }
}

class CustomComponents extends JComponent {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 300);
    }

    @Override
    public Dimension getMaximumSize() {
        return new Dimension(800, 600);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}

FLowLayout布局管理器不会重新分配可用空间; 它使用每个组件的首选大小(请参阅Java API中的FlowLayout文档)。

我个人会将您的包装器面板的布局管理器更改为GridBagLayout ,并将您的centerPanel添加到其中,指定一个适当的GridBagConstraints对象来根据需要处理空间分布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM