簡體   English   中英

While 循環導致更新 JTextField 出現問題 [暫停]

[英]While loop causing issues with updating JTextField [on hold]

因此,該代碼旨在成為一個使用字符來表示事物的簡單游戲,但是當 ac(Cat) 或 ab(Bat) 被擊中時,游戲會凍結並且 JTextField 不會正確更新。 我將問題縮小到 while 循環,但我不明白為什么它不起作用。 這是我的代碼 -

import java.util.ArrayList;
import java.io.*;
import java.lang.reflect.*;
import java.lang.Math;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Main {
  public static int posX = 9;
  public static int posY = 5;
  public static int posXPast = 9;
  public static int posYPast = 5;
  public static int cposXPast = 9;
  public static int cposYPast = 5;
  public static int chance = 99;
  public static int cTamed = 0;
  public static String row1 = "";
  public static String row2 = "";
  public static String row3 = "";
  public static String row4 = "";
  public static String row5 = "";
  public static String row6 = "";
  public static String row7 = "";
  public static String row8 = "";
  public static String row9 = "";
  public static String row10 = "";
  public static String row11 = "";
  public static boolean upTest = false;
  public static boolean downTest = false;
  public static boolean leftTest = false;
  public static boolean rightTest = false;
  public static int testOne = 0;
  public static int testTwo = 0;
  public static int testThree = 0;
  public static boolean enterTest = false;
  public static JTextField row1L = new JTextField();
  public static JTextField row2L = new JTextField();
  public static JTextField row3L = new JTextField();
  public static JTextField row4L = new JTextField();
  public static JTextField row5L = new JTextField();
  public static JTextField row6L = new JTextField();
  public static JTextField row7L = new JTextField();
  public static JTextField row8L = new JTextField();
  public static JTextField row9L = new JTextField();
  public static JTextField row10L = new JTextField();
  public static JTextField row11L = new JTextField();
  public static JTextField output = new JTextField();
  public static JTextField output2 = new JTextField();
  public static String[] set = new String[0];
  public static CreateReadOnlyJTextField CreateReadOnlyJTextField = new CreateReadOnlyJTextField();
  public static MKeyListener MKeyListener = new MKeyListener();
  public static String saveName = "test1.sav";
  public static String [] [] board = new String [11] [11];
  public static void boardInit() {
    for (int i = 0; i < 11; i++) {
      for (int a = 0; a < 11; a++) {
        board[i][a] = "   ";
      }
    }
    for (int tRow = 0; tRow < 11; tRow++) {
      board[0][tRow] = "x  ";
      board[tRow][0] = "x  ";
      board[10][tRow] = "x  ";
      board[tRow][10] = "x  ";
    }
    board [0] [5] = "   ";
    board [posX][posY] = "@  ";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
  }
  public static void boardUpdate() {
    if (cTamed == 1) {
      board [posXPast][posYPast] = "c  ";
      board [cposXPast][cposYPast] = "   ";
      cposXPast = posXPast;
      cposYPast = posYPast;
    }else {
      board [posXPast][posYPast] = "   ";
    }
    board [posX][posY] = "@  ";
    posXPast = posX;
    posYPast = posY;
    row1 = "";
    row2 = "";
    row3 = "";
    row4 = "";
    row5 = "";
    row6 = "";
    row7 = "";
    row8 = "";
    row9 = "";
    row10 = "";
    row11 = "";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
    mainRecall();
  }
  public static void mainRecall() {
    int levelFin = 0;
    if (posX == 0 && posY == 5) {
      levelFin = 1;
    }
    if (upTest == true) {
      upTest = false;
      if (posX > 0) {
        if(board[posX - 1][posY].equals("B  ")) {
          hitB(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("*  ")) {
          hitStar(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("C  ")) {
          hitC(posX - 1, posY);
        }else if(board[posX - 1][posY].equals("S  ")) {
          output2.setText("You hit a statue!");
          boardUpdate();
        }
      }
      if (levelFin == 1) {
        newLevel();
      }else {
        if (posX == 1 && posY != 5) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posX--;
        }
        boardUpdate();
      }
    }
    else if (downTest == true) {
      downTest = false;
      if(board[posX + 1][posY].equals("B  ")) {
        hitB(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("*  ")) {
        hitStar(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("C  ")) {
        hitC(posX + 1, posY);
      }else if(board[posX + 1][posY].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posX == 9) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posX++;
        }
        boardUpdate();
      }
    }else if (leftTest == true) {
      leftTest = false;
      if(board[posX][posY - 1].equals("B  ")) {
        hitB(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("*  ")) {
        hitStar(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("C  ")) {
        hitC(posX, posY - 1);
      }else if(board[posX][posY - 1].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posY == 1 || posX == 0) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posY--;
        }
        boardUpdate();
      }
    }else if (rightTest == true) {
      rightTest = false;
      if(board[posX][posY + 1].equals("B  ")) {
        hitB(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("*  ")) {
        hitStar(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("C  ")) {
        hitC(posX, posY + 1);
      }else if(board[posX][posY + 1].equals("S  ")) {
        output2.setText("You hit a statue!");
        boardUpdate();
      }else {
        if (posY == 9 || posX == 0) {
          output2.setText("This path is blocked by a wall.");
        }else {
          posY++;
        }
        boardUpdate();
      }
    }else if (enterTest == true) {
      enterTest = false;
      try {
        FileOutputStream saveFile = new FileOutputStream(saveName);
        ObjectOutputStream save = new ObjectOutputStream(saveFile);
        save.writeObject(posX);
        save.writeObject(posY);
        save.writeObject(posXPast);
        save.writeObject(posYPast);
        save.writeObject(chance);
        save.writeObject(board);
        save.close();
      } catch (Exception exc) {
        exc.printStackTrace();
      }
    }
  }
  public static void newLevel (){
    chance--;
    posX = 9;
    posY = 5;
    posXPast = 9;
    posYPast = 5;
    for (int i = 0; i < 11; i++) {
      for (int a = 0; a < 11; a++) {
        board[i][a] = "   ";
      }
    }
    for (int tRow = 0; tRow < 11; tRow++) {
      board[0][tRow] = "x  ";
      board[tRow][0] = "x  ";
      board[10][tRow] = "x  ";
      board[tRow][10] = "x  ";
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "B  ";
        }
      }
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "C  ";
        }
      }
    }
    for (int i = 1; i < 10; i++) {
      for (int a = 1; a < 10; a++) {
        int rand = (int)(Math.random() * 101);
        if (rand > chance) {
          board[i][a] = "*  ";
        }
      }
    }
    board [0] [5] = "   ";
    board [posX][posY] = "@  ";
    row1 = "";
    row2 = "";
    row3 = "";
    row4 = "";
    row5 = "";
    row6 = "";
    row7 = "";
    row8 = "";
    row9 = "";
    row10 = "";
    row11 = "";
    for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
    row1L.setText(row1);
    row2L.setText(row2);
    row3L.setText(row3);
    row4L.setText(row4);
    row5L.setText(row5);
    row6L.setText(row6);
    row7L.setText(row7);
    row8L.setText(row8);
    row9L.setText(row9);
    row10L.setText(row10);
    row11L.setText(row11);
    mainRecall();
  }
  public static void hitC(int cPosX, int cPosY) {
    int tAttempted = 0;
    int jAttempted = 0;
    int bAttempted = 0;
    String tAttemptedI = "t";
    String jAttemptedI = "j";
    String bAttemptedI = "b";
    int counter = 1;
    int success = 0;
    String out = "Would you like to ";
    ArrayList<String> vars = new ArrayList<String>();
    output2.setText("You hit a cat!");
    while(success != 1) {
      if (tAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to tame it?";
        counter++;
        vars.add(tAttemptedI);
      }
      if (jAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to jump over it?";
        counter++;
        vars.add(jAttemptedI);
      }
      if (bAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to bait it away?";
        counter++;
        vars.add(bAttemptedI);
      }
      if (tAttempted + jAttempted + bAttempted == 3) {
        output2.setText("The cat turned into a statue...");
        board[cPosX][cPosY] = "S  ";
        success = 1;
        break;
      }
      output2.setText(out);
      if (testOne + testTwo + testThree > 3 - tAttempted + jAttempted + bAttempted || testOne + testTwo + testThree < 1 || testOne + testTwo + testThree > counter - 1) {
          testOne = 0;
          testTwo = 0;
          testThree = 0;
          output2.setText("Invalid response");
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("t")) {
        int seed = (int)(Math.random() * 101);
        if (seed > 50) {
          output2.setText("Success! The cat was tamed and will now follow you!");
          cTamed = 1;
          board[cPosX][cPosY] = "   ";
          success = 1;
        }else {
          output2.setText("Failed!"); 
          vars.remove((testOne + testTwo + testThree) - 1);
          tAttempted = 1;
        }
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("j")) {
        int seed2 = (int)(Math.random() * 101);
        if (seed2 > 50) {
          output2.setText("Success! You jumped over the cat and avoided it, but it is still there!");
          success = 1;
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          jAttempted = 1;
        }
      }else if (vars.get((testOne + testTwo + testThree) - 1).equals("b")) {
        int seed3 = (int)(Math.random() * 101);
        if (seed3 > 50) {
          output2.setText("Success! You baited the cat away!");
          success = 1;
          board[cPosX][cPosY] = "   ";
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          bAttempted = 1;
        }
      }
      counter = 1;
    }
    testOne = 0;
    testTwo = 0;
    testThree = 0;
    boardUpdate();
  }
  public static void hitB(int bPosX, int bPosY) {
    int tAttempted = 0;
    int jAttempted = 0;
    int bAttempted = 0;
    String tAttemptedI = "t";
    String jAttemptedI = "j";
    String bAttemptedI = "b";
    int counter = 1;
    int success = 0;
    String out = "Would you like to ";
    ArrayList<String> vars = new ArrayList<String>();
    output2.setText("You hit a bat!");
    while(success != 1) {
      if (tAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to tame it?";
        counter++;
        vars.add(tAttemptedI);
      }
      if (jAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to jump over it?";
        counter++;
        vars.add(jAttemptedI);
      }
      if (bAttempted == 0) {
        out += "\n" + counter + ". ";
        out += "Try to bait it away?";
        counter++;
        vars.add(bAttemptedI);
      }
      if (tAttempted + jAttempted + bAttempted == 3) {
        output2.setText("The bat turned into a statue...");
        board[bPosX][bPosY] = "S  ";
        success = 1;
        break;
      }
      output2.setText(out);
      if (testOne + testTwo + testThree > 3 - tAttempted + jAttempted + bAttempted || testOne + testTwo + testThree < 1 || testOne + testTwo + testThree > counter - 1) {
        output2.setText("Invalid response");
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("t")) {
        int seed = (int)(Math.random() * 101);
        if (seed > 50) {
          output2.setText("Success! The bat was tamed and will now follow you!");
          cTamed = 1;
          board[bPosX][bPosY] = "   ";
          success = 1;
        }else {
          output2.setText("Failed!"); 
          vars.remove(testOne + testTwo + testThree - 1);
          tAttempted = 1;
        }
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("j")) {
        int seed2 = (int)(Math.random() * 101);
        if (seed2 > 50) {
          output2.setText("Success! You jumped over the bat and avoided it, but it is still there!");
          success = 1;
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          jAttempted = 1;
        }
      }else if (vars.get(testOne + testTwo + testThree - 1).equals("b")) {
        int seed3 = (int)(Math.random() * 101);
        if (seed3 > 50) {
          output2.setText("Success! You baited the bat away!");
          success = 1;
          board[bPosX][bPosY] = "   ";
        }else {
          output2.setText("Failed!");
          vars.remove(testOne + testTwo + testThree - 1);
          bAttempted = 1;
        }
      }
      counter = 1;
    }
    boardUpdate();
  }
  public static void hitStar(int sPosX, int sPosY) {
    output2.setText("You consumed a star and gained 10 health!");
    board[sPosX][sPosY] = "   ";
    boardUpdate();
  }
  public static void main(String[] args) {
    CreateReadOnlyJTextField.main(set);
    try {
      FileInputStream saveFile = new FileInputStream(saveName);
      ObjectInputStream save = new ObjectInputStream(saveFile);
      posX = (int) save.readObject();
      posY = (int) save.readObject();
      posXPast = (int) save.readObject();
      posYPast = (int) save.readObject();
      chance = (int) save.readObject();
      board = (String[][]) save.readObject();
      row1 = row2 = row3 = row4 = row5 = row6 = row7 = row8 = row9 = row10 = row11 = "";
      for (int r1 = 0; r1 < 11; r1++) {
        row1 += board[0][r1];
        row2 += board[1][r1];
        row3 += board[2][r1];
        row4 += board[3][r1];
        row5 += board[4][r1];
        row6 += board[5][r1];
        row7 += board[6][r1];
        row8 += board[7][r1];
        row9 += board[8][r1];
        row10 += board[9][r1];
        row11 += board[10][r1];
      }
      save.close();
      mainRecall();
    } catch (Exception exc) {
      try {
        FileOutputStream saveFile = new FileOutputStream(saveName);
        ObjectOutputStream save = new ObjectOutputStream(saveFile);
        save.writeObject(posX);
        save.writeObject(posY);
        save.writeObject(posXPast);
        save.writeObject(posYPast);
        save.writeObject(chance);
        save.writeObject(board);
        save.close();
        boardInit();
        mainRecall();
      } catch (Exception exc1) {
        exc.printStackTrace();
      }
    }
  }
}
class CreateReadOnlyJTextField extends JFrame {
  private static final long serialVersionUID = 1L;
  public CreateReadOnlyJTextField() {
    this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), 1));
    Main.row1L.setText("X    X    X    X    X    X    X    X    X    X    X");
    Main.row2L.setText("X                                                 X");
    Main.row3L.setText("X                                                 X");
    Main.row4L.setText("X                                                 X");
    Main.row5L.setText("X                                                 X");
    Main.row6L.setText("X                                                 X");
    Main.row7L.setText("X                                                 X");
    Main.row8L.setText("X                                                 X");
    Main.row9L.setText("X                                                 X");
    Main.row10L.setText("X                        @                        X");
    Main.row11L.setText("X    X    X    X    X    X    X    X    X    X    X");
    Main.output.setText("Which direction would you like to travel, or would you rather SAVE your path");
    Main.output2.setText("");
    Main.row1L.setEditable(false);
    Main.row2L.setEditable(false);
    Main.row3L.setEditable(false);
    Main.row4L.setEditable(false);
    Main.row5L.setEditable(false);
    Main.row6L.setEditable(false);
    Main.row7L.setEditable(false);
    Main.row8L.setEditable(false);
    Main.row9L.setEditable(false);
    Main.row10L.setEditable(false);
    Main.row11L.setEditable(false);
    Main.output.setEditable(false);
    Main.output2.setEditable(false);
    JTextField textField = new JTextField();
    textField.addKeyListener(new MKeyListener());
    Main.row1L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row2L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row3L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row4L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row5L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row6L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row7L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row8L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row9L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row10L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.row11L.setFont(new Font("Courier", Font.PLAIN, 20));
    Main.output.setFont(new Font("Courier", Font.PLAIN, 16));
    Main.output2.setFont(new Font("Courier", Font.PLAIN, 16));
    add(textField);
    add(Main.row1L);
    add(Main.row2L);
    add(Main.row3L);
    add(Main.row4L);
    add(Main.row5L);
    add(Main.row6L);
    add(Main.row7L);
    add(Main.row8L);
    add(Main.row9L);
    add(Main.row10L);
    add(Main.row11L);
    add(Main.output);
    add(Main.output2);
  }
  private static void createAndShowGUI() {
    JFrame frame = new CreateReadOnlyJTextField();
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI(); 
      }
    });
  }
}

class MKeyListener extends KeyAdapter {
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyText(e.getKeyCode()).equals("Up") || e.getKeyText(e.getKeyCode()).equals("W")) {
      Main.upTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Down") || e.getKeyText(e.getKeyCode()).equals("S")) {
      Main.downTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Left") || e.getKeyText(e.getKeyCode()).equals("A")) {
      Main.leftTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Right") || e.getKeyText(e.getKeyCode()).equals("D")) {
      Main.rightTest = true;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("1")) {
      Main.testOne = 1;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("2")) {
      Main.testTwo = 2;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("3")) {
      Main.testThree = 3;
      Main.mainRecall();
    }else if (e.getKeyText(e.getKeyCode()).equals("Enter")) {
      Main.enterTest = true;
      Main.mainRecall();
    }
  }
}

請幫我...

看起來您在 UI 線程上做了很多工作。 如果您在另一個線程中運行mainRecall() ,您可能會擁有一個響應速度更快的應用程序。 出於這個原因,游戲通常有一個在屏幕上繪制內容的 UI 線程和一個或多個執行計算密集型工作的后台線程。 通常在后台線程中有一個永久運行循環的概念,它只檢查(和調整)每個游戲元素的 position,檢查一個 object 是否擊中另一個,等等,而不是檢查在給定鍵是按下。

后台線程的偽代碼示例是:

while(true) {
  for each nonPlayerObject
    processNextMove()
    checkForCollision()
  end for
  for each playerObject
    processNextMove()
    checkForCollision()
    recalculateScore()
  end for
  sleep(5)
}

在 UI 線程上,您還可以偵聽用戶輸入並將其傳遞給后台線程,例如,可以立即重繪玩家的動作。

在 Java 中,您可以創建並運行一個新線程

new Thread(new Runnable() {
        public void run() {
            while(true) {
               System.out.println("I am running in a background thread");
               try { Thread.sleep(100); } catch (InterruptedException e) {}
            }
        }
}).start();

有關創建和運行線程的更多信息,請參閱http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html#anonymous-implementation-of-runnable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM