How do I make a new random image appear with a button press in Java?

Viewed 124

I want to make it so that when the user presses the Roll Dice button, the program displays a new random picture of a die. I have it set up so that it should change the file name of the displayed image, but it doesn't actually change the image. It just shows the initialized one.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class GraphicPanel extends JPanel {

    BufferedImage img = null;
    private int index = 0;
    String random = "one.png";

    String[] imageFileNameArray = new String[] {"one.png", "two.png", "three.png", "four.png", "five.png", "six.png"};

    GraphicPanel() {
        this.setBackground(Color.WHITE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        String fileName = ("src/images/" + random);

        try {
            img = ImageIO.read(new File(fileName));
        } catch (IOException ex) {
            Logger.getLogger(GraphicPanel.class.getName()).log(Level.SEVERE, null, ex);
        }

        g.drawImage(img, 200, 50, 100, 100, this);
    }

    public void newRoll(){
        int idx = new Random().nextInt(imageFileNameArray.length);
        String random = (imageFileNameArray[idx]);
        System.out.println(random);
        this.repaint();
    }
}
1 Answers

You need to add a button to the Jframe during setup and register an event listener whose method does what newRoll() does.

Related