I need to restrict a certain proportion of a JFrame so that the layout of what I want to display on it is not distorted, but I would not want to have to block resize with setRezisable()
. The minimum aspect ratio for testing is 350x500 (7:10 ratio), but I would like to keep that ratio every time the screen changes size.
I've done an example to see how it looks:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class KeepAspectRatioTest extends JFrame {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 350;
private static final int HEIGHT = 500;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
KeepAspectRatioTest screen = new KeepAspectRatioTest();
screen.setVisible(true);
});
}
public KeepAspectRatioTest() {
initUI();
}
private void initUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setTitle("Keep Aspect Ratio");
JPanel board = new JPanel();
board.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
JPanel sidePanel = new JPanel();
sidePanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.red));
sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS));
sidePanel.setPreferredSize(new Dimension(WIDTH/6, HEIGHT));
add(board, BorderLayout.CENTER);
add(sidePanel, BorderLayout.EAST);
pack();
setLocationRelativeTo(null);
}
}
How do I keep the aspect ratio of the screen after resizing?
Q: I think I need to use a ComponentListener
, I just do not know how to control it with this listener, especially since, by allowing resizing, it is also enabled to maximize the screen.