Search code examples
javagraphics2d

Image is not drawing on top left of panel


When i load image ,it do not load at upper left (if the image is large to be fit on window size).This is because i diminish its size as shown in code. Although i am giving its coordinate value 0,0 it is not drawing at that position.

import javax.swing.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class photo extends JFrame 
{
Dimension screenwidth=getToolkit().getScreenSize();
int mx=(int)screenwidth.getWidth(); 
int my=(int)screenwidth.getHeight();
BufferedImage picture1;
JLabel label3;
int neww;
int newh;
    public photo() {

    JFrame f = new JFrame("Image Editor v1.0");
    f.setLayout(null);
    try{
        File file=new File("e:\\8.jpg");
            picture1=ImageIO.read(file);
    }catch(Exception e)
    {

    }

    JPanel panel2 = new JPanel();
    panel2.setLayout(null);
    panel2.setBounds(101,20,mx-100,my-20);
    f.add(panel2);
    label3 = new JLabel("");
    label3.setBounds(110,30,mx-110,my-30);
    panel2.add(label3);
    f.setExtendedState(Frame.MAXIMIZED_BOTH);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BufferedImage bi = null;

            if(picture1.getWidth()>mx-110 ||picture1.getHeight()>my-30 )
            {

                 neww= (int) Math.round(picture1.getWidth() * 0.25);
                newh = (int) Math.round(picture1.getHeight() *0.25);
            }
            else
            {
                neww=picture1.getWidth();
                newh=picture1.getHeight();

            }
            bi = new BufferedImage(neww,newh,BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = (Graphics2D) bi.createGraphics();
            g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
            g2d.drawImage(picture1,0,0,neww,newh,0,0,picture1.getWidth(),picture1.getHeight(), null);
           label3.setIcon(new ImageIcon(bi));

    }

public static void main(String[] args) 
{
    new photo();

}

}

Solution

  • You could add g2d.translate(0, 0); between g2d.addRenderingHints and g2d.drawImage and try it.

    EDIT

    So if you want the image to be at 101 px and 20 px, you should label3.setBounds(0,0,neww,newh); after label3.setIcon(new ImageIcon(bi)); instead of the current. I think this shall work as I have just tested.