简体   繁体   English

While 循环导致更新 JTextField 出现问题 [暂停]

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

So, the code is intended to be a simple game that uses characters to represent things, but when either ac(Cat) or ab(Bat) is hit, the game freezes and the JTextField doesn't update correctly.因此,该代码旨在成为一个使用字符来表示事物的简单游戏,但是当 ac(Cat) 或 ab(Bat) 被击中时,游戏会冻结并且 JTextField 不会正确更新。 I narrowed the issue down to the while loop but I cant understand why it doesn't work.我将问题缩小到 while 循环,但我不明白为什么它不起作用。 Here is my code -这是我的代码 -

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();
    }
  }
}

Please help me...请帮我...

It looks like you're doing a LOT of work on the UI thread.看起来您在 UI 线程上做了很多工作。 You will probably have a more responsive application if you run mainRecall() inside another thread.如果您在另一个线程中运行mainRecall() ,您可能会拥有一个响应速度更快的应用程序。 Games usually have a UI thread that draws things on-screen and one or more background threads that do the computationally-intensive work for just this reason.出于这个原因,游戏通常有一个在屏幕上绘制内容的 UI 线程和一个或多个执行计算密集型工作的后台线程。 Often there's a concept of a perpetually-running loop in the background thread that just checks (and adjusts) the position of each game element, checks to see if one object has hit another, etc instead of checking performing those actions when a given key is pressed.通常在后台线程中有一个永久运行循环的概念,它只检查(和调整)每个游戏元素的 position,检查一个 object 是否击中另一个,等等,而不是检查在给定键是按下。

A pseudo-code example of the background thread is:后台线程的伪代码示例是:

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

On the UI thread you might also listen for user input and pass it to the background thread, eg so the player's movements can be redrawn immediately.在 UI 线程上,您还可以侦听用户输入并将其传递给后台线程,例如,可以立即重绘玩家的动作。

In Java you can create and run a new thread with在 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();

For more information on creating and running threads, see http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html#anonymous-implementation-of-runnable有关创建和运行线程的更多信息,请参阅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