我有一个项目接受用户的每个骰子上的骰子数和面数。它将滚动用户想要的模具数量,显示每个模具落在的面上,并显示所有模具的总数。这正是我的程序应该做的。
但是,所有这些都应该发生在JFrame和JPanel中。正如您所看到的,我有GUI代码,但由于它不起作用,它目前已被注释掉。所有内容最初都会正确显示,标签,按钮和文本框......但我不知道如何使“滚动”按钮工作。
截至目前,单击“滚动”按钮时没有任何反应。我不知道如何让它发挥作用。我需要程序的GUI部分来显示每个模具落在的面上以及点击“滚动”按钮时所有模具的总数。
我希望在我的程序正常运行时删除DiceRollerTest()
代码,并且仅使用showGUI()
。
有人能引导我朝正确的方向前进吗?
以下是我的主要代码DiceRollerTest()
,ShowUI()
和ShowGUI()
代码...
public static void main(String[] args)
{
//showGUI();
showUI();
}
public void DiceRollerTest()
{
try
{
d = new DiceBag(6,6);
}
catch (FaceRangeException e){System.out.println(e.getMessage()); return;}
catch (DiceRangeException e){System.out.println(e.getMessage()); return;}
System.out.println(d.getClass());
int total = d.roll();
System.out.println(Integer.toString(total)+" "+d.toString());
}
static void showUI()
{
Scanner keyboardInput = new Scanner(System.in);
String input;
int numberOfDice;
int numberOfFaces;
System.out.println("Enter number of dice to roll:");
input = keyboardInput.nextLine();
numberOfDice = Integer.parseInt(input);
System.out.println("Enter number of faces:");
input = keyboardInput.nextLine();
numberOfFaces = Integer.parseInt(input);
try
{
d = new DiceBag(numberOfDice, numberOfFaces);
}
catch (FaceRangeException e){System.out.println(e.getMessage());}
catch (DiceRangeException e){System.out.println(e.getMessage());}
d.roll();
System.out.println("Rolls: "+d.toString());
System.out.println("Total: "+d.getTotal());
keyboardInput.close();
static void showGUI()
{
JFrame frame = new JFrame("Dice Roller");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DiceRollerPanel panel = new DiceRollerPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
以下是我的DiceRollerPanel()
和RollButtonListener
代码...
public DiceRollerPanel()
{
numberOfDiceLabel = new JLabel("Enter Number of Dice:");
dice = new JTextField(5);
numberOfFacesLabel = new JLabel("Enter Number of Faces:");
faces = new JTextField(5);
rollButton = new JButton("Roll");
rollButton.addActionListener(new RollButtonListener());
displayRolls = new JLabel("Rolls:");
total = new JLabel("Total:");
add(numberOfDiceLabel);
add(dice);
add(numberOfFacesLabel);
add(faces);
add(rollButton);
add(displayRolls);
add(total);
setPreferredSize(new Dimension(225,100));
setBackground(Color.gray);
}
private class RollButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
displayRolls.setText("Rolls:");
total.setText ("Total:");
DiceBag.roll();
}
}