Java graphic.drawImage 没有出现

Java graphic.drawImage not appearing

我加载了一张图片,但是当我尝试显示它时什么也没有出现。

public class JComponentButton extends JComponent implements MouseListener {

BufferedImage image;

public static void main(String[] args) {
    JFrame mainFrame = new JFrame("Test Title3");
    mainFrame.setSize(400,400);
    mainFrame.setLayout(new GridLayout(1,1));
    mainFrame.addWindowListener(new WindowAdapter() {
       @Override public void windowClosing(WindowEvent windowEvent){ 
          System.exit(0);
       }        
    }); 

    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new FlowLayout());

    JComponentButton button = new JComponentButton();
    button.setSize(64,64);
    controlPanel.add(button);

    mainFrame.add(controlPanel);
    mainFrame.setVisible(true);

    System.out.println("finishing");
}

public JComponentButton(){
    super();
    try {
        this.image = ImageIO.read(new File("resources/default.png"));
    } catch (IOException e) {
        System.out.println("did not load image");
        System.exit(1);
    }
    enableInputMethods(true);
    addMouseListener(this);
}

@Override public void paintComponent(Graphics g){
    super.paintComponent(g);
    System.out.println(image.getHeight() + "," + image.getWidth());
    g.drawImage(image, 64, 64, null);
}

图像似乎已加载,因为 64,64 打印到控制台中。但是它应该出现在 window 上的地方是空白的。我使用 g.fillRect 在那里毫无问题地画了一个正方形。所以看起来问题必须出在 g.drawImage 上。我也尝试将视角从 null 更改为这个,但没有任何改变。

在您的代码中,方法 g.drawImage(image, 64, 64, null) 将以全分辨率绘制您的图像 从偏移量 64、64.

开始

drawImage 的 Javadoc:

Draws as much of the specified image as is currently available. The image is drawn with its top-left corner at (x, y) in this graphics context's coordinate space. Transparent pixels in the image do not affect whatever pixels are already there.

这意味着虽然您的图像确实在绘制,但它是在按钮的可见坐标 space 之外绘制的。

要解决此问题,如果图像的大小符合组件的大小,请将 64, 64 替换为 0, 0,或者使用更明确的方法 drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) 来指定图像应该是什么在按钮中调整大小。

例如

g.drawImage(image, 0, 0, null); //draws image at full resolution

g.drawImage(image, 0, 0, 64, 64, null); //draws image at offset 0, for max resolution of 64x64 

您看不到图像是因为图像绘制在按钮之外。 由于按钮外没有任何面板,因此无法绘制。

原因是,您指定的图像的 x 轴和 y 轴,i.e.Top 左角为 64,64,按钮大小为 64,64.Thus,此图像将绘制在按钮的右下角,即按钮的角点。 因此,您应该将图像点指定为 0,0(这些是图像的左上角),以便它将覆盖按钮的 0,0(这些是按钮的左上角)点。

此外,您必须指定 image.So 的宽度和高度,这样它就不会超出 button.If 的边界。您不想指定宽度和高度,那么您必须将图像的像素减少到按钮的大小(至少)。

您可以将代码重写为: g.drawImage(image,0,0,64,64,null);