java - java 中的 Tic Tac Toe 重置按钮

标签 java jtextarea tic-tac-toe

我添加了一个按钮来停止游戏,但我不知道如何添加监听器,也不知道如何在单击按钮时调用方法。请告诉我如何使重置按钮正常工作。谢谢。

   private String[] board = new String[ 9 ]; // tic-tac-toe board
   private JTextArea outputArea; // for outputting moves
   private Player[] players; // array of Players
  private ServerSocket server; // server socket to connect with clients
  private int currentPlayer; // keeps track of player with current move
  private final static int PLAYER_X = 0; // constant for first player
   private final static int PLAYER_O = 1; // constant for second player
  private final static String[] MARKS = { "X", "O" }; // array of marks
  private ExecutorService runGame; // will run players
  private Lock gameLock; // to lock game for synchronization
  private Condition otherPlayerConnected; // to wait for other player
  private Condition otherPlayerTurn; // to wait for other player's turn
  private boolean win;
 public TicTacToeServer()
  {
  super( "Tic-Tac-Toe Server" ); // set title of window

  // create ExecutorService with a thread for each player
  runGame = Executors.newFixedThreadPool( 2 );
  gameLock = new ReentrantLock(); // create lock for game

  // condition variable for both players being connected
  otherPlayerConnected = gameLock.newCondition();

  // condition variable for the other player's turn
  otherPlayerTurn = gameLock.newCondition();      

  for ( int i = 0; i < 9; i++ )
     board[ i ] = new String( "" ); 
  players = new Player[ 2 ]; // create array of players
  currentPlayer = PLAYER_X; // set current player to first player

  try
  {
     server = new ServerSocket( 12345, 2 ); // set up ServerSocket
  } // end try
  catch ( IOException ioException ) 
  {
     ioException.printStackTrace();
     System.exit( 1 );
  } // end catch

  outputArea = new JTextArea(); // create JTextArea for output
  add( outputArea, BorderLayout.CENTER );
  JButton reset= new JButton ("Reset");
  add(reset, BorderLayout.SOUTH);
  reset.setActionCommand("reset");
  //reset.addActionListener(this);
  outputArea.setText( "Server awaiting connections\n" );


  setSize( 300, 300 ); // set size of window
  setVisible( true ); // show window
  } // end TicTacToeServer constructor

最佳答案

你应该使用ActionListener:

将其注册到按钮,实现将包含单击按钮后自动调用的代码。 这就是java事件系统的工作原理。

这是教程 Action Listeners

关于java - java 中的 Tic Tac Toe 重置按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11535294/

相关文章:

java - 将字节数组转换为 bufferedimage 结果为 null

java - 如何使用 Selenium 3.3.1 获取 Safari 10 主要版本号?

java - JTextArea 上的 KeyEvent 问题

c++ - 测试井字游戏中可能获胜的可能性

c# - C# 中的 Tic Tac Toe MiniMax?

java - 如何更改 Android DatePickerDialog 中的字体

java - 将字符串解析为 double

java - JTextArea和JScrollBar的交互问题

java - 使 JTextArea 可滚动

python - 如何使用 guizero 知道谁是 python 井字游戏的赢家