如何在 Java 中锁定 gridLayout 的纵横比? [英] How to lock aspect ratio of a gridLayout in Java?

查看:41
本文介绍了如何在 Java 中锁定 gridLayout 的纵横比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以在 Java Swing 中锁定 GridLayout 组件的纵横比?或者这应该在包含该布局的 JPanel 上完成?

Is there an easy way of locking the aspect ratio of a GridLayout component in Java Swing ? Or should this be done on the JPanel containing that layout ?

推荐答案

GridLayout 有效地忽略了组件的首选大小,但您可以控制 纵横比 paintComponent() 中绘制的任何内容,如下所示 示例.渲染的形状保持圆形(1:1 纵横比),同时(几乎)以最窄的维度填充容器.调整框架大小以查看效果.

GridLayout effectively ignores a component's preferred size, but you can control the aspect ratio of whatever is drawn in paintComponent(), as shown in this example. The rendered shape remains circular (1:1 aspect), while (nearly) filling the container in the narrowest dimension. Resize the frame to see the effect.

附录:例如,我添加了 CirclePanelN * N 个实例 到下面的 GridLayout.

Addendum: For example, I added N * N instances of CirclePanel to a GridLayout below.

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

/**
 * @see https://stackoverflow.com/a/9858355/230513
 * @see https://stackoverflow.com/a/3538279/230513
 */
public class SwingPaint {

    private static final int N = 4;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setLayout(new GridLayout(N, N));
                for (int i = 0; i < N * N; i++) {
                    frame.add(new CirclePanel());
                }
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    private static class CirclePanel extends JPanel {

        private static final Random r = new Random();

        public CirclePanel() {
            this.setPreferredSize(new Dimension(80, 80));
            this.setForeground(new Color(r.nextInt()));
            this.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {
                    CirclePanel.this.update();
                }
            });
        }

        public void update() {
            this.setForeground(new Color(r.nextInt()));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Dimension size = this.getSize();
            int d = Math.min(size.width, size.height) - 10;
            int x = (size.width - d) / 2;
            int y = (size.height - d) / 2;
            g.fillOval(x, y, d, d);
            g.setColor(Color.blue);
            g.drawOval(x, y, d, d);
        }
    }
}

这篇关于如何在 Java 中锁定 gridLayout 的纵横比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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