开发者

Java - Change BufferedImage File

I have a Java class that extends JPanel and implements MouseListener, and trying to duplicate some basic functionality of JButton but with some loaded images to make things more pretty. Here's some slices of my code.

A class field:

private BufferedImage image;

In the constructor I have:

try {
    image = ImageIO.read(new File("image/firstImage.png"));
} catch (IOException ex) {
}

I then override paintComponent to draw the image:

public void paintComponent(Graphics g) {
    g.drawImage(image, 0, 0, null);
}

And that works great! Hooray. But I want to also be able to change the image that is being drawn to the screen. This doesn't work:

public void mousePressed(MouseEvent arg0) {
        try {
            image = ImageIO.read(new File("image/newImage.png"));
        } catch (IOException ex) {
     开发者_开发知识库   }
}

mousePressed() definitely fires successfully (tried a System.out.println() debug statement) so what do I have to do to successfully change the image being drawn?


Your image is updated but the window is not painted again. Try to call repaint(); after that. It should help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜