I have a simple function that generates JFrame containing an image:
//The window
JFrame frame = new JFrame();
//Topmost component of the window
Container main = frame.getContentPane();
//Turns out this is probably the simplest way to render image on screen
//with guaranteed 1:1 aspect ratio
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
//Put the image drawer in the topmost window component
main.add(panel);
//Set window size to the image size plus some padding dimensions
frame.setSize(image.getWidth(null)+1, image.getHeight(null)+15);
frame.setVisible(true);
Result:
I think this happens because the window dimensions include the size of the top bar and the window borders.
I also tried to set the size for JPanel
and call pack()
on JFrame:
//Set the size to the panel and let JFrame size itself properly
panel.setSize(image.getWidth(null), image.getHeight(null));
frame.pack();
Result is even worse:
So how can I precisely specify the inner window dimensions in pixels?