Home > Software design >  Java Swing image cut off/zoomed
Java Swing image cut off/zoomed

Time:01-07

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 500x500, just like my frame, but it still comes out wrong. This also applies to when I use the function like this:

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.

CodePudding user response:

Don't set the size of the frame

If your image is 500x500 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.

  •  Tags:  
  • Related