为按钮分配字符串值-JavaFx

时间:2018-12-22 22:54:43

标签: java string javafx

我正在尝试创建井字游戏,并且我为每个按钮创建了9个字符串值。按下按钮后,它会根据是X还是O为它分配一个字符串值。最后,我将所有字符串连接起来,向控制台输出了一个成功消息,但它似乎不起作用。

按钮代码

            // Create a Button
    Button TopLeft = new Button("");
    root.getChildren().add(TopLeft);
    // Move the Button
    TopLeft.setTranslateX(-150);
    TopLeft.setTranslateY(-150);
    // Action for the Button
    // Code from: https://docs.oracle.com/javafx/2/ui_controls/button.htm
    TopLeft.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            if (playerX == true) {
                TopLeft.setText("X");
                 tl = "X";

            } else {
                TopLeft.setText("O");
                 tl = "O";

            }

            playerX = !playerX;
            TopLeft.setDisable(true);
        }

    });

获胜条件

//WIN CONDITION, r1 = row 1, c1 = column 1, d1 = diagonal 1, etc        
     r1 = tl + tm + tr;
     r2 = l + m + r;
     r3 = bl + bm + br;
     c1 = tl + l + bl;
     c2 = tm + m + bm;
     c3 = tr + r + br;
     d1 = tl + m + br;
     d2 = tr + m + bl;


    if((r1.equals("XXX") || r2.equals("XXX") || r3.equals("XXX") || c1.equals("XXX") || c2.equals("XXX") || c3.equals("XXX") || d1.equals("XXX") || d2.equals("XXX")) == true){
        System.out.println("Player X Wins");
    } else {
        System.out.println("Player O Wins");
    }

2 个答案:

答案 0 :(得分:0)

将这样的操作命令添加到引用的按钮上:

    TopLeft.setActionCommand("ButtonX");

在您的handle方法中

    String action = e.getActionCommand();

    if (action.equals("ButtonX") {
           // code here
    }  

答案 1 :(得分:0)

尝试检查单击按钮后是否立即赢得了玩家。您可能想要创建一种方法来检查玩家是否赢了,如图所示:

private boolean playerWon(){
     r1 = tl + tm + tr;
     r2 = l + m + r;
     r3 = bl + bm + br;
     c1 = tl + l + bl;
     c2 = tm + m + bm;
     c3 = tr + r + br;
     d1 = tl + m + br;
     d2 = tr + m + bl;


     return ((r1.equals("XXX") || r2.equals("XXX") || r3.equals("XXX") || 
              c1.equals("XXX") || c2.equals("XXX") || c3.equals("XXX") || 
              d1.equals("XXX") || d2.equals("XXX") ||

              r1.equals("OOO") || r2.equals("OOO") || r3.equals("OOO") || 
              c1.equals("OOO") || c2.equals("OOO") || c3.equals("OOO") || 
              d1.equals("OOO") || d2.equals("OOO")))
}

然后在切换匝数之前调用此方法。在playerX = !playerX;之前。你可以做这样的事情

TopLeft.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            if (playerX == true) {
                TopLeft.setText("X");
                 tl = "X";

            } else {
                TopLeft.setText("O");
                 tl = "O";

            }

            if(playerWon()){
               if(playerX) System.out.println("Player X Wins");
               else System.out.println("Player O Wins");
            }

            playerX = !playerX;
            TopLeft.setDisable(true);
        }

});