如何等待MouseListener按下鼠标? [英] How to wait for a MouseListener mouse press?

查看:79
本文介绍了如何等待MouseListener按下鼠标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我知道以前曾有人问过这个问题,但是根据我的程序的当前结构,这些答案将不起作用.我有一个井字游戏.在游戏算法中,当用户的时间轮到我时,我调用它来获取X&的方法.鼠标单击的Y坐标.但是,我希望这种方法首先提示用户单击,然后等待用户单击,然后获得x&要使用的游戏算法的点击次数y.目前,它只是拉x&上一次单击的y,使用户没有时间在轮到他们时开始单击.我唯一需要解决的问题是在2个线程上运行游戏和用户代码并睡一觉.但是,这似乎过于复杂,我宁愿不这样做.整个情况似乎是一个非常基本的问题,在执行代码之前等待鼠标单击.我该怎么做呢?

So, I know this question has been asked before, but thoes answers will not work for the current structure of my program. I have a game of tic-tac-toe. In the games algorithm, when its time for a users turn I have it call a method to get the X & Y coords of a Mouse Click. However, I would like this method to first prompt a user for a click, then wait for the user to click, THEN get the x & y of the click for the game algorithm to use. Currently, it is just pulling the x & y of the last click giving no time for the user to click when their turn starts. The only thought I had to fix this problem was running the game and user code on 2 threads and having one sleep. But, this seems overly complex and I'd prefer not to do this. The whole situation seems like a very fundamental problem, waiting for a mouseclick before executing code. How do I do this?

void takeTurn() {

        //turnCount++;

        while(gameOver == false) {


        if (turn == 'O') {
            O.getInput();
            if(board[O.x][O.y] != '\u0000') continue;
            board[O.x][O.y] = 'O';
        }
        else if (turn == 'X') {
            X.getInput();
            if(board[X.x][X.y] != '\u0000') continue;
            board[X.x][X.y] = 'X';
        }

        printBoard();
         if (checkWinner(turn) == turn) {
            System.out.println("Winner: " + turn);
        }



        if (turn == 'O') turn = 'X';
        else if (turn == 'X') turn = 'O';

    }


    }

getInput()是获取x&的方法. y.

getInput() is the method that gets the x & y.

public void getInput() {

    System.out.println("Click on your tile");
    //wait for click here
    //then get x & y of click
} 

好的,因此,使用ActionListener时,如何让线程等待执行某个动作?

Okay, so using an ActionListener, how do I have a thread wait until an action is preformed?

推荐答案

关键不是要等待"鼠标输入,而是要根据程序的状态将程序的行为更改为鼠标按下.例如,如果您正在做井字游戏,则需要为程序提供一个变量,让它知道轮到谁了,这可能是一个简单的布尔变量,例如

The key is not to "wait" for the mouse input, but rather, to change the behavior of the program to mouse press depending on its state. For instance, if you're doing tic-tac-toe, you'll want to give the program a variable to let it know whose turn it is, and this could be a simple boolean variable, say

private boolean xTurn = true;

当此变量为true时,为X圈,为false时,为O圈.

When this variable is true, it's X's turn, when false, it is O's turn.

然后在您的MouseListener(如果是Swing应用程序)中,使用变量帮助确定操作,然后在使用它之后将布尔值切换到下一个状态.例如:

Then in your MouseListener (if a Swing application), use the variable to help decide what to do, and then after using it, toggle the boolean to the next state. For example:

// within mouse listener
if (xTurn) {
    label.setForeground(X_COLOR);
    label.setText("X");
} else {
    label.setForeground(O_COLOR);
    label.setText("O");
}
// toggle value held by boolean variable.
xTurn = !xTurn;

例如:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

@SuppressWarnings("serial")
public class TicTacToePanel extends JPanel {
    private static final int ROWS = 3;
    private static final int MY_C = 240;
    private static final Color BG = new Color(MY_C, MY_C, MY_C);
    private static final int PTS = 60;
    private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS);
    public static final Color X_COLOR = Color.BLUE;
    public static final Color O_COLOR = Color.RED;
    private JLabel[][] labels = new JLabel[ROWS][ROWS];
    private boolean xTurn = true;

    public TicTacToePanel() {
        setLayout(new GridLayout(ROWS, ROWS, 2, 2));
        setBackground(Color.black);

        MyMouse myMouse = new MyMouse();
        for (int row = 0; row < labels.length; row++) {
            for (int col = 0; col < labels[row].length; col++) {
                JLabel label = new JLabel("     ", SwingConstants.CENTER);
                label.setOpaque(true);
                label.setBackground(BG);
                label.setFont(FONT);
                add(label);
                label.addMouseListener(myMouse);
            }
        }
    }

    private class MyMouse extends MouseAdapter {
        @Override // override mousePressed not mouseClicked
        public void mousePressed(MouseEvent e) {
            JLabel label = (JLabel) e.getSource();
            String text = label.getText().trim();
            if (!text.isEmpty()) {
                return;
            }
            if (xTurn) {
                label.setForeground(X_COLOR);
                label.setText("X");
            } else {
                label.setForeground(O_COLOR);
                label.setText("O");
            }

            // information to help check for win
            int chosenX = -1;
            int chosenY = -1;
            for (int x = 0; x < labels.length; x++) {
                for (int y = 0; y < labels[x].length; y++) {
                    if (labels[x][y] == label) {
                        chosenX = x;
                        chosenY = y;
                    }
                }
            }
            // TODO: check for win here
            xTurn = !xTurn;
        }
    }

    private static void createAndShowGui() {
        TicTacToePanel mainPanel = new TicTacToePanel();

        JFrame frame = new JFrame("Tic Tac Toe");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

这篇关于如何等待MouseListener按下鼠标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆