import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SimpleRoll extends JFrame 
        implements ActionListener
{

  private Die die;
  private JLabel rollValue;
  private JButton rollButton;
  private ImageIcon[] faces;

  public SimpleRoll()
  {
    super("Simple View Example");

    // create the die and its faces
    this.die = new Die();
    this.faces = new ImageIcon[6];
    for (int i = 1; i <= 6; i++)
	{
      String filename = String.valueOf(i) + ".png";
      ImageIcon icon = createImageIcon(filename, "");
      faces[i - 1] = icon;
    }

    // create the label that shows the face value
    this.rollValue = new JLabel("1", this.faces[0], JLabel.CENTER);
    
    // create the button that lets the user roll the die
    this.rollButton = new JButton("Roll");
    this.rollButton.addActionListener(this);

    // create an object to arrange the layout
    this.setLayout(new GridLayout(2, 1));
    
    // add the label and button to the frame
    this.add(rollValue);
    this.add(rollButton);
    this.pack();

    // what to do when the user closes the app
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  protected ImageIcon createImageIcon(String path, String description)
  {
    java.net.URL imgURL = getClass().getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL, description);
    } else {
      System.err.println("Couldn't find file: " + path);
      return null;
    }
  }

  public static void main(String[] args)
  {
    SimpleRoll app = new SimpleRoll();
    app.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent e)
  {
    this.die.roll();
    int value = this.die.getValue();
    String sval = String.valueOf(value);
    this.rollValue.setText(sval);
    this.rollValue.setIcon(this.faces[value - 1]);
  }

}
