java生成界面显示输赢
时间: 2023-09-22 18:07:28 浏览: 45
要让Java界面显示输赢,可以使用Swing或JavaFX来创建用户界面。具体实现方法如下:
1. 创建一个包含游戏逻辑的类。
2. 在该类中编写判断输赢的逻辑代码,并将结果保存到一个变量中。
3. 在用户界面中添加一个标签或文本框,用于显示输赢结果。
4. 在用户界面的代码中,调用游戏逻辑类的判断输赢方法,并将结果显示在标签或文本框中。
以下是一个简单的示例程序,演示如何在JavaFX界面中显示输赢结果:
```java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Game extends Application {
private boolean hasWon = false;
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setPadding(new Insets(10));
Button btn1 = new Button("Rock");
btn1.setOnAction(event -> {
determineWinner("Rock");
updateResultLabel();
});
Button btn2 = new Button("Paper");
btn2.setOnAction(event -> {
determineWinner("Paper");
updateResultLabel();
});
Button btn3 = new Button("Scissors");
btn3.setOnAction(event -> {
determineWinner("Scissors");
updateResultLabel();
});
hbox.getChildren().addAll(btn1, btn2, btn3);
root.setCenter(hbox);
Label resultLabel = new Label("Result: ");
root.setBottom(resultLabel);
Scene scene = new Scene(root, 300, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
private void determineWinner(String userChoice) {
// Game logic to determine the winner
// Set the hasWon variable to true or false based on the result
}
private void updateResultLabel() {
// Update the result label based on the hasWon variable
String resultText = "Result: ";
if (hasWon) {
resultText += "You won!";
} else {
resultText += "You lost!";
}
((Label) ((BorderPane) ((HBox) ((BorderPane) Scene.
getCurrent().getRoot()).getCenter()).getChildren().get(0)).getBottom()).setText(resultText);
}
public static void main(String[] args) {
launch(args);
}
}
```
在该示例程序中,我们在`determineWinner`方法中编写了判断输赢的逻辑代码,并将结果保存到一个布尔型变量`hasWon`中。然后在`updateResultLabel`方法中,我们根据`hasWon`变量的值来更新界面中的标签文本。在JavaFX中,可以通过`Scene`对象的`getRoot`方法获取界面的根节点,然后使用`getChildren`方法获取子节点。由于我们在`BorderPane`的底部添加了一个标签,所以我们可以通过以下代码获取该标签:`((Label) ((BorderPane) ((HBox) ((BorderPane) Scene.getCurrent().getRoot()).getCenter()).getChildren().get(0)).getBottom()`。最后,我们可以使用`setText`方法更新标签的文本内容。