I am making a board game and I need to action a button which operates like a dice. In my frame, I have the throw dice button and next to it is a JLabel which would show the result of the dice. The problem is that I have a coding for dice in a different class and the button in another. I have an action class which would hold the code for action listener. How can I implement it? Below is my code.
GameView Class:
public void gui()
{
BorderLayout borderlayout = new BorderLayout();
//Creates the frame, set the visibility to true, sets the size and exit on close
JFrame frame = new JFrame("Games");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates the Throw Dice button
Panel p = new Panel();
p.setLayout(new GridLayout());
p.add(new Button("Throw Dice"));
p.add(new Label("Dice Draw")); //This is where I want the dice result to be shown when hit the button
p.setBackground(new Color(156, 93, 82));
frame.add(p, BorderLayout.SOUTH);
Dice Class:
public class Dice
{
//stores the dice result in the variable
private int diceResult;
/**
* Constructor for objects of class Dice
*/
public Dice()
{
this.diceResult = diceResult;
}
/**
* Generates a random number between 1 and 5
*/
public void randomGenerator ()
{
Random dice = new Random();
diceResult = dice.nextInt(5)+1;
System.out.println(diceResult);
}
}
Action Class:
public class Action
{
public void actionPerformed (ActionEvent e)
{
}
}
In simple example like this i can recommend you to use advantages of anonymous class which implements
ActionListenerlike this.Also you must add
getDiceResultmethod to yourDiceclass.