2012-07-18 78 views
1

我已經添加了一個按鈕來休息遊戲,但我不知道如何添加一個偵聽程序或者當我點擊按鈕時如何調用方法。請告訴我如何獲得重置按鈕的工作。謝謝。java中的Tic Tac Toe Reset按鈕

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 

回答

0

你應該使用的ActionListener:

它註冊到按鈕和實施將包含一旦按鈕被點擊,將被自動調用的代碼。 這是java事件系統的工作原理。

這裏是一個教程Action Listeners

0

您可以添加一個動作聽者只是這樣

reset.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) 
     { 
     //Execute when button is pressed 
     }   
    });  
+0

我添加了監聽器和執行,但沒有任何反應: reset.setActionCommand(「重置」); reset.addActionListener(新的ActionListener(){ 公共無效的actionPerformed(ActionEvent的E) { \t對(INT I = 0; I <9;我++) \t板[I] =新字符串( 「」); \t players = new Player [2]; \t currentPlayer = PLAYER_X; player } }); – user1222521 2012-07-18 07:30:21

+0

當玩家轉彎時,你如何重新粉刷棋盤。 – 2012-07-19 00:24:22