4
I need to restrict a certain proportion of a Jframe so that the layout of what I want to display on it isn’t distorted, but I wouldn’t want to have to block resizing with setRezisable()
. The minimum ratio testing you is 350x500 (7:10 ratio), but I would like to keep this ratio whenever the screen has changed size.
I made 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 maintain the screen ratio after resizing?
P.S.: I believe you need to use a ComponentListener
, I just don’t know how to control it with this Resizer, especially since, by allowing resizing, it is also enabled that the screen is maximized.
What is the reason for the negative? Can I no longer have a question on the site? Negative just doesn’t help me realize how much my doubt "does not demonstrate research effort, is not clear or is not useful".
– user28595
Man, I’ve tried to solve your problem in a lot of ways, both elegant and gambit, and I haven’t been able to yet. I am surprised that such a thing does not seem to have a simple solution. When/if it achieves this, put an answer.
– Victor Stafusa
@Victorstafusa I saw some answers in Soen, but none of them can actually solve it, it seems. In one of them, it is suggested to rewrite the window resize class at hand to restrict this.
– user28595
I also reviewed Soen and tried to tinker with internal details of
java.awt.Window
and I couldn’t.– Victor Stafusa