简体   繁体   English

等到结束方法之前单击JButton

[英]Wait until a JButton is clicked before ending a method

I am programming a game of tic tac toe that takes turns between a player (a user clicking buttons) and a computer player. 我正在编写一个tic tac toe游戏,它在玩家(用户点击按钮)和计算机玩家之间轮流进行。

I have a method called playersTurn() that needs to wait until a JButton is clicked before the method ends and the computer player takes its turn. 我有一个名为playersTurn()的方法,需要等到方法结束之前点击JButton并且计算机播放器轮到它。 I have read about using threads and a wait - notify method, but I am new to Java and can't figure out how to implement this. 我已经阅读过有关使用线程和wait - notify方法的内容,但我是Java新手,无法弄清楚如何实现它。

I was wondering if there is a simpler way of overcoming this problem or if this is the only way, and if so could anyone direct me towards a good tutorial? 我想知道是否有一种更简单的方法来克服这个问题,或者这是唯一的方法,如果是这样,有人能指导我找一个好的教程吗?

Thanks 谢谢

U should not wait and test that something happen, The proper way is to set Listener to Butoon and for example change active player after button click. U不应该等待并测试发生的事情,正确的方法是将Listener设置为Butoon,例如在按钮点击后更改活动播放器。 But everything depends on your code implemantation. 但一切都取决于您的代码实现。

As @HFOE said (+1 to him) you dont want to use Thread s with notify and wait thats really overcomplicating things The logic for your game is skewed IMO. 正如@HFOE所说的那样(对他来说+1)你不想使用带有通知的 Thread等待那真的过于复杂的东西你的游戏的逻辑是倾斜的IMO。

Before starting the game lay down some framework: 在开始游戏之前放下一些框架:

  • 9 JButton s (array will hold the buttons) 9 JButton (数组将按住按钮)
  • JPanel with a GridLayout(3,3) to create a tic tac toe grid 带有GridLayout(3,3) JPanel创建一个tic tac toe网格

Now comes the important part: 现在来了重要的部分:

  • Player starts the game and thereafter computer goes and so on 玩家启动游戏,然后计算机启动,依此类推

With the above in mind see my example I made the basics is inside the ActionListener used for each button after the player has gone (button has been clicked and player symbol set), we call the method for the cpu to play : 考虑到上面的内容,我看到了我的例子,基本内容是在播放器消失后用于每个按钮的ActionListener内(点击按钮并设置了播放器符号),我们调用cpu的方法来播放

在此输入图像描述

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class Test {
    //declare variables for player and cpu symbol

    private String playerSymbol = "X";
    private String cpuSymbol = "O";
    //used for cpu to select random block
    private Random r = new Random();
    //create arraylist to hold buttons
    ArrayList<JButton> blocks = new ArrayList<>();
    //this is the action listner that will be added to each block and will allow player the first turn then cpu goes
    private ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {

            //players turn
            playerTurn(ae);

            //check for win after player gone
            checkForWin();

            //cpu turn
            cpuTurn();

            //check for a win after cpu goes
            checkForWin();
        }

        private void cpuTurn() {
            System.out.println("CPU goes");
            while (true) {
                int blockNumber = r.nextInt(9);

                System.out.println(blockNumber + "");
                String tmp = blocks.get(blockNumber).getText();

                if (tmp.equals("")) {
                    blocks.get(blockNumber).setText(cpuSymbol);
                    break;
                }
            }
        }

        private void checkForWin() {
            System.out.println("Checking for a win...");
        }

        private void playerTurn(ActionEvent ae) {
            System.out.println("Player goes");
            JButton block = (JButton) ae.getSource();
            block.setText(playerSymbol);
        }
    };

    public Test() {
        initComponents();
    }

    private void initComponents() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel board = new JPanel(new GridLayout(3, 3));//create gridlayput to hold buttons

        //create blocks/Jbuttons to hold X and Y
        createBlocks(blocks);
        //add buttons/blocks to the board
        fillBoard(blocks, board);
        //add board to JFrame content pane
        frame.add(board);

        frame.pack();
        frame.setVisible(true);
    }

    private void fillBoard(ArrayList<JButton> blocks, JPanel board) {
        for (JButton block : blocks) {
            board.add(block);
        }
    }

    private void createBlocks(ArrayList<JButton> blocks) {
        for (int i = 0; i < 9; i++) {

            //create new button with a size of 50,50
            JButton block = new JButton() {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(50, 50);
                }
            };
            block.addActionListener(al);//add the actionlistner to the button
            blocks.add(block);
        }
    }

    public static void main(String[] args) {
        //set L&F and create UI on EDT
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                try {//set L&F
                    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (Exception e) {
                    // If Nimbus is not available, you can set the GUI to another look and feel.
                }

                //create UI
                new Test();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM