Java Swing How to - Lock aspect ratio of a GridLayout








Question

We would like to know how to lock aspect ratio of a GridLayout.

Answer

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
/*from w ww  .  j  a v a  2  s .  co m*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  static int N = 4;

  public static void main(String[] args) {
    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);
  }
}

class CirclePanel extends JPanel {
  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) {
        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);
  }
}