Java:如何控制JPanel长宽比? [英] Java: How to control JPanel aspect ratio?

查看:568
本文介绍了Java:如何控制JPanel长宽比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPanel,我希望它保持正方形但是我希望它的大小,以便它填充其父JFrame中可能的最大空间量但保持方形,即它采用JFrame的最短边作为方形宽度。

I have a JPanel which I want to remain a square however I want it to size so that it fills the maximum amount of space possible in its parent JFrame but remains square i.e. it takes the shortest side of the JFrame as the square width.

我搜索了网络,检查了所有布局管理器,似乎没有一个解决这个非常简单的问题的简单方法。

I've searched the net, checked all layout managers and none seem to have a simple solution to this very simple problem.

推荐答案

您可以使用 GridBagLayout ComponentListener

例如:(灵感来自: https://community.oracle.com/thread/1265752?start=0&tstart=0

public class AspectRatio {
    public static void main(String[] args) {
        final JPanel innerPanel = new JPanel();
        innerPanel.setBackground(Color.YELLOW);

        final JPanel container = new JPanel(new GridBagLayout());
        container.add(innerPanel);
        container.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                resizePreview(innerPanel, container);
            }
        });
        final JFrame frame = new JFrame("AspectRatio");
        frame.getContentPane().add(container);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    private static void resizePreview(JPanel innerPanel, JPanel container) {
        int w = container.getWidth();
        int h = container.getHeight();
        int size =  Math.min(w, h);
        innerPanel.setPreferredSize(new Dimension(size, size));
        container.revalidate();
    }
}

这篇关于Java:如何控制JPanel长宽比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆