图像未绘制在面板的左上角

Image is not drawing on top left of panel

当我加载图像时,它不会加载到左上角(如果图像大到适合 window 尺寸)。这是因为我缩小了它的尺寸,如代码所示。虽然我给它的坐标值 0,0 但它没有在那个位置绘制。

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();

}

}

你可以在g2d.addRenderingHintsg2d.drawImage之间加上g2d.translate(0, 0);试试看。

编辑

因此,如果您希望图像为 101 像素和 20 像素,您应该在 label3.setIcon(new ImageIcon(bi)); 之后 label3.setBounds(0,0,neww,newh); 而不是当前。我认为这应该像我刚刚测试的那样工作。