用 Java 为类项目构建一个简单的石头剪刀布 GUI 游戏。
尝试采用 MVC 方法,我将下面 resultsGUI()
中的代码从我的“Controller”类移到了“View”类。
我尝试在 Controller 类中创建 View 类的实例并调用如下方法:view.resultsGUI();
但这在我的编译器中引发了异常错误。
我如何调用驻留在我的 View 类中的 resultsGUI
方法在 chooseWinner()
方法(也在下面)的底部执行,就像代码所做的那样它是 chooseWinner()
的一部分?
我是新手,感谢您的帮助。
下面的 chooseWinner 方法:
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("匹配结果"); 容器面板 = 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);
}
最佳答案
您的控件应该有 View 和模型的实例,而不仅仅是任何 View 和模型实例,而是当前可视化的 Activity View 和当前使用的模型。像这样的东西可能在你的类(class)中有 main 方法:
public static void main(String[] args) {
View view = new View();
Model model = new Model();
Control control = new Control(view, model);
// start the GUI up
}
在您的 Control 类中,您将使用构造函数参数来设置类字段:
public class Control {
private View view;
private Model model;
public Control(View view, Model model) {
this.view = view;
this.model = model;
}
// now your control can call model and view methods.
// ....
}
关于java - 从Java中的单独类文件调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311633/