简体   繁体   English

如何在Java swing中跟踪鼠标点击作为输入

[英]How to track mouse clicks as input in Java swing

I'm working on a personal project where I'm trying to create Simon game in Java.我正在做一个个人项目,我正在尝试用 Java 创建 Simon 游戏。 It is essentially a memory game where the user has to repeat the sequence the computer generates.它本质上是一个记忆游戏,用户必须重复计算机生成的序列。 So, I created a basic CLI version of the game and now I'm looking to give it a GUI.所以,我创建了游戏的基本 CLI 版本,现在我希望给它一个 GUI。 I haven't worked with Java Swing before so I'm having some trouble replicating the same behavior in GUI form.我之前没有使用过 Java Swing,所以在以 GUI 形式复制相同的行为时遇到了一些麻烦。

The structure of the CLI version looked something like this: CLI 版本的结构如下所示:

public static void main(String[] args) {
        GameContext simon = new GameContext();
        simon.start();
        
        while (!simon.getRoundEndState()) {
            simon.playSequence();
            simon.pickColour();
        }   
}

Here's what the playSequence() method looks like.这是 playSequence() 方法的样子。 It essentially generates a number between 0 and 3 and keeps adding one number to the array each round if the player gets the previous one right.它本质上生成一个 0 到 3 之间的数字,并且如果玩家正确地获得了前一个数字,则每一轮都会向数组中添加一个数字。

    public void playSequence() {
        int rand = getRandomNumber(4);
        computerSequence.add(rand);
        for(int i:computerSequence) {
            System.out.println(i);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        gameContext.setState(gameContext.getHumanPlayingState());   
    }

pickColour() method that asks the user for the pattern and checks if the pattern matches the one generated by the computer. pickColour() 方法向用户询问模式并检查该模式是否与计算机生成的模式匹配。

    public void pickColour() {
        boolean roundWon = true;
        for(int i=0; i<gameContext.getSequence().size();i++){
            Scanner input = new Scanner(System.in);
            Integer userInput = input.nextInt();
            if(userInput == gameContext.getSequence().get(i)) {
                continue;
            }
            else {
                System.out.println("Input mismatched the sequence");
                roundWon = false;
                break;
            }
        }
        
        if (roundWon == true) {
            score++;
            gameContext.setState(gameContext.getComputerPlayingState());
        } else {
            gameContext.setRoundEndState(true);
            System.out.println("Your score is: " + score);
            gameContext.setState(gameContext.getInLobbyState());
        }
        
        
    }

Please note that I'm using the state pattern here and hence the change in states.请注意,我在这里使用了状态模式,因此状态发生了变化。 I got the first part working where I need to light up the colors after the computer generates the the sequence.我得到了第一部分,在计算机生成序列后,我需要点亮颜色。 So now, playSequence() looks something like this:所以现在, playSequence() 看起来像这样:

    public void playSequence() {
        int rand = getRandomNumber(4);
        computerSequence.add(rand);
        gameContext.setState(gameContext.getHumanPlayingState());   
    }

And I added a mouse listener to the start button which looks something like this:我在开始按钮上添加了一个鼠标监听器,它看起来像这样:

        btnStart.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                simon = new GameContext();
                
                simon.start();
                
                while (!simon.getRoundEndState()) {
                    simon.playSequence();
                    for(int i : simon.getSequence()) {
                        lightPanels(i);
                        Timer timer = new Timer(1000, e -> {
                            darkenPanels(i);
                        });
                        timer.setRepeats(false);
                        timer.start();
                    
                    }
                    simon.pickColour();
                }

            }
        });

I have 4 JPanels that now act as the input buttons.我有 4 个 JPanel 现在充当输入按钮。 How do I change simon.pickColour() so that instead the asking the user for the correct sequence like it did in the CLI version, it would register the clicks made in the JPanels as the input.我如何更改 simon.pickColour() 以便不像在 CLI 版本中那样要求用户输入正确的序列,而是将在 JPanel 中进行的点击注册为输入。

It essentially generates a number between 0 and 3 and keeps adding one number to the array each round if the player gets the previous one right.它本质上生成一个 0 到 3 之间的数字,并且如果玩家正确地获得了前一个数字,则每一轮都会向数组中添加一个数字。

and

I have 4 JPanels that now act as the input buttons.我有 4 个 JPanel 现在充当输入按钮。

Why have 4 panels.为什么有4个面板。 Just have one panel that contains 4 buttons.只需一个包含 4 个按钮的面板。 You would then add an ActionListener to the button (not a MouseListner) to handle the clicking of the button.然后将 ActionListener 添加到按钮(不是 MouseListner)来处理按钮的点击。

The buttons would be created with code like:按钮将使用如下代码创建:

for (int i = 1; i <= 4; i++)
{
    JButton button = new JButton("" + i);
    button.addActionListener(...);
    panel.add( button );
}

The ActionListener code would then get the text of the button and add the text to an ArrayList to track the order the the buttons that have been clicked. ActionListener代码然后将获取按钮的文本并将文本添加到 ArrayList 以跟踪已单击按钮的顺序。

A working example of this approach of sharing an ActionListener for all the buttons can be found here: https://stackoverflow.com/a/33739732/131872 .可以在此处找到这种为所有按钮共享 ActionListener 的方法的工作示例: https : //stackoverflow.com/a/33739732/131872 Note the "action command" will default from the text that is set on the button.请注意,“操作命令”将默认来自按钮上设置的文本。

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

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