是否有一种简单的方法可以在 Java Swing 中锁定 GridLayout 组件的纵横比?还是应该在包含该布局的 JPanel 上完成?
问问题
2885 次
1 回答
7
GridLayout
有效地忽略了组件的首选大小,但您可以控制所绘制内容的纵横比paintComponent()
,如本例所示。渲染的形状保持圆形(1:1 纵横比),同时(几乎)以最窄的尺寸填充容器。调整框架大小以查看效果。
附录:例如,我在下面添加了N * N
实例。CirclePanel
GridLayout
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);
}
}
}
于 2012-03-25T06:34:47.533 回答