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

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 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.

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

wDmaU.png

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

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值