繁体   English   中英

如何在 Java 中锁定 gridLayout 的纵横比?

[英]How to lock aspect ratio of a gridLayout in Java?

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

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

附录:例如,我在下面的GridLayout中添加了N * NCirclePanel实例。

在此处输入图片说明

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);
        }
    }
}

暂无
暂无

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

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