gpt4 book ai didi

java - 无法使用 JavaFX 获取标签来更新其文本

转载 作者:行者123 更新时间:2023-12-05 03:17:48 25 4
gpt4 key购买 nike

我是一名尝试通过 Java MOOC fi 类(class)学习 Java 的初学者。我正在尝试玩井字游戏。我正在尝试向按钮添加功能,以便当我按下它们时,顶部的信息标签会发生变化(显示轮到谁了),但我无法更新标签。我试着自己查找解决方案,但我真的想不通。

package ticTacToe;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.util.ArrayList;

public class TicTacToeApplication extends Application {
ArrayList<Button> buttons = new ArrayList<>();
String currentPlayer = "X";

public static void main(String[] args) {
launch(TicTacToeApplication.class);
}

@Override
public void start(Stage window) throws Exception{
BorderPane layout = new BorderPane();
layout.setPadding(new Insets(20));

Label info = new Label("Turn: " + currentPlayer);
info.setFont(Font.font(40));

GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);

//create 9 buttons with the same functionality
for (int i = 0; i < 9; i++) {
Button button = new Button();
button.setFont(Font.font(20));
button.setMinSize(40,40);
button.setMaxSize(40, 40);

//button functionality
button.setOnMouseClicked(event -> {
button.setText(currentPlayer);
changeTurn();
info.setText("Turn: " + currentPlayer);
});
buttons.add(button);
}
//add buttons to the grid
int buttonNr = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j <3; j++) {
grid.add(buttons.get(buttonNr),i,j);
buttonNr++;
}
}

//setup main layout
layout.setTop(info);
layout.setCenter(grid);

//setup and start scene
Scene scene = new Scene(layout);
window.setTitle("TicTacToe");
window.setScene(scene);
window.show();
}

public void changeTurn(){
if (currentPlayer.equals("X")) {
currentPlayer = "O";
}
if (currentPlayer.equals("O")) {
currentPlayer = "X";
}
}
}

最佳答案

作为 James_D said ,问题是 changeTurn 方法中的一个非常基本的问题。我总是变回 X 的回合。

我在第一个 if 中添加了 return,现在它可以工作了。

public void changeTurn(){
if (currentPlayer.equals("X")) {
currentPlayer = "O";
return;
}
if (currentPlayer.equals("O")) {
currentPlayer = "X";
}

关于java - 无法使用 JavaFX 获取标签来更新其文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73907249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com