Three days ago I wrote about a Java Dice Roller I wrote. I've now added a GUI to that program. Here it is:
DiceRollerGUI.java:
package com.egroegnosbig.dicerollergui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DiceRollerGUI {
static JFrame frameOne = new JFrame("Dice Roller");
public static void main(String[] args) {
frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DiceGUI GUI = new DiceGUI();
frameOne.add(GUI);
Button b = new Button("Roll");
b.addActionListener(new ButtonAction());
frameOne.add(b);
frameOne.setLayout(new GridLayout(1, 2));
frameOne.setSize(400, 250);
frameOne.setResizable(false);
frameOne.setVisible(true);
}
}
class ButtonAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
DiceRollerGUI.frameOne.setVisible(false);
JFrame frameTwo = new JFrame("Dice Roller");
frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameTwo.setSize(400, 250);
frameTwo.setResizable(false);
ResultGUI resultGUI = new ResultGUI();
frameTwo.add(resultGUI);
frameTwo.setVisible(true);
}
}
DiceGUI.java:
package com.egroegnosbig.dicerollergui;
import java.awt.*;
import javax.swing.*;
public class DiceGUI extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.drawString("Dice Roller", 70, 20);
}
}
ResultGUI.java:
package com.egroegnosbig.dicerollergui;
import java.awt.*;
import javax.swing.*;
public class ResultGUI extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
Dice dice = new Dice(6);
int resultInt = dice.roll();
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(resultInt);
String result = sb.toString();
g.drawString("The dice rolled a", 150, 125);
g.drawString(result, 243, 125);
}
}
Dice.java:
package com.egroegnosbig.dicerollergui;
import java.util.Random;
public class Dice {
private final Random rand;
private final int faces;
public Dice(int faces) {
this.rand = new Random();
this.faces = faces;
}
public int roll() {
return rand.nextInt(faces) + 1;
}
}
Working on better class names...