我正在制作一个棋盘游戏,我需要操作一个像骰子一样操作的按钮。在我的框架中,我有掷骰子按钮,旁边是一个 JLabel,它将显示骰子的结果。问题是我有一个不同类中的骰子编码和另一个类中的按钮。我有一个动作类,它将保存动作侦听器的代码。我该如何实施?下面是我的代码。
游戏视图类:
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);
骰子类:
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);
}
}
动作类:
public class Action
{
public void actionPerformed (ActionEvent e)
{
}
}