为 Java 中的类项目构建一个简单的 Rock Paper Scissors GUI 游戏。
尝试使用 MVC 方法,我将resultsGUI()
下面的代码从“控制器”类移到“视图”类。
我尝试在 Controller 类中创建 View 类的实例并像这样调用该方法:view.resultsGUI();
但这在我的编译器中引发了异常错误。
如何调用resultsGUI
驻留在我的 View 类中的方法以在方法的底部chooseWinner()
(也在下面)执行,就像代码在它的一部分时所做的那样chooseWinner()
?
我是新手,感谢您的帮助。
selectWinner 方法如下:
public static void chooseWinner(int x) {
playerChoice = x;
String winningCombo = "" + Math.min(compChoice, playerChoice)
+ Math.max(compChoice, playerChoice);
switch (Integer.parseInt(winningCombo)) {
case 1:
text = "Paper wins!";
if (playerChoice == 2) {
playerWon = 1;
}
break;
case 2:
text = "Rock wins!";
if (playerChoice == 1) {
playerWon = 1;
}
break;
case 3:
text = "Scissors wins!";
if (playerChoice == 3) {
playerWon = 1;
}
break;
}
if (playerWon == 1) {
text1 = "Congrats, you win!";
playerWon = 0;
win = win + 1;
total = total + 1;
} else if (playerWon == 2) {
text1 = "It's a tie!";
playerWon = 0;
} else {
text1 = "Computer wins!";
total = total + 1;
}
}
resultsGUI 方法如下: public void resultsGUI() { JFrame rFrame = new JFrame("Match Results"); 容器面板 = rFrame.getContentPane(); panel.setLayout(null);
JLabel l0 = new JLabel(controller.text1 + controller.text);
l0.setBounds(75, 10, 300, 35);
panel.add(l0);
//show the result in a new splash screen
JLabel l1 = new JLabel("Human's Choice");
l1.setBounds(40, 35, 150, 35);
panel.add(l1);
JLabel l2 = new JLabel("Computer's Choice");
l2.setBounds(215, 35, 150, 35);
panel.add(l2);
JLabel l3 = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/image/" + (controller.playerChoice - 1) + ".jpg"));
l3.setBounds(10, 100, 170, 60);
panel.add(l3);
JLabel l4 = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/image/" + (controller.compChoice - 1) + ".jpg"));
l4.setBounds(200, 100, 170, 60);
panel.add(l4);
JLabel l5 = new JLabel("Win/Loss rate: " + controller.win + "/" + controller.total);
l5.setBounds(125, 25, 150, 350);
panel.add(l5);
JLabel l6 = new JLabel("Tie: " + controller.tie);
l6.setBounds(125, 30, 125, 370);
panel.add(l6);
rFrame.setSize(400, 270);
rFrame.setVisible(true);
}