Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Swing image cut off/zoomed

when I try to render a png image in Java Swing, it is cut off/zoomed on all sides. Here is my code:

this.setSize(500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.getGraphics().drawImage(getImage("IMAGE PATH"), 0, 0, this);

And this is my getImage function

public static Image getImage(String path) {
        File file = new File(path);
        try {
             return ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

The image I want to render is 500×500, just like my frame, but it still comes out wrong. This also applies to when I use the function like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Image image = getImage("Image Path");
assert image != null;
JLabel picLabel = new JLabel(new ImageIcon(image));

Here is one of the images I am trying to render:
Image

Here is the outcome:
Outcome
It is kind of hard to tell from this example, but the ground should be lower and the trees higher.

>Solution :

Don’t set the size of the frame

If your image is 500×500 then how can you expect the image size and frame size to be the same when the frame also has a title bar and borders?

Don’t do custom painting`

Instead:

  1. create a JLabel with an ImageIcon.
  2. Add the label to the frame
  3. invoke pack() before making the frame visible.

All the components will get the proper size.

Read the Swing tutorial on How to Use Labels for more information and examples.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading