[英]How to lock aspect ratio of a gridLayout in Java?
是否有一種簡單的方法可以在 Java Swing 中鎖定 GridLayout 組件的縱橫比? 或者這應該在包含該布局的 JPanel 上完成?
GridLayout
有效地忽略了組件的首選大小,但您可以控制在paintComponent()
繪制的任何內容的縱橫比,如本例所示。 渲染的形狀保持圓形(1:1 縱橫比),同時(幾乎)以最窄的維度填充容器。 調整框架大小以查看效果。
附錄:例如,我在下面的GridLayout
中添加了N * N
個CirclePanel
實例。
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.