如何在Java中锁定gridLayout的宽高比?

时间:2012-03-25 02:47:04

标签: java swing layout gridbaglayout

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

1 个答案:

答案 0 :(得分:7)

GridLayout实际上会忽略组件的首选大小,但您可以控制paintComponent()中所绘制内容的aspect ratio,如此example所示。渲染的形状保持圆形(1:1宽高比),同时(几乎)以最窄的尺寸填充容器。调整框架大小以查看效果。

附录:例如,我向N * N添加了GridLayoutimport 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); } } } 个实例。

enter image description here

{{1}}