1

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:

image description

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:

image description

So how can I precisely specify the inner window dimensions in pixels?

image description

Here's the full function code.

1 Answers1

2

Specify the preferred size of the panel by overriding the getPreferredSize method of JPanel and calling pack() on the JFrame before making it visible

JPanel panel = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
    @Override
    public Dimension getPreferredSize(){
        return new Dimension(image.getWidth(), image.getHeight());
    }
};

See the answers in Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components on the use and effect of either this technique, or the setPreferredSize method

Community
  • 1
  • 1
copeg
  • 8,092
  • 17
  • 27