简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM