简体   繁体   English

Java-数字游戏-同一类中的多个ActionListener

[英]Java - Number Game - Multiple ActionListener in the Same Class

I am only 6 - 7 weeks into learning Java, so I apologize in advance if my code is sloppy or terminology is off. 我学习Java的时间只有6-7周,所以如果我的代码草率或术语不正确,我会向您道歉。 I'm trying to create program that creates a random number and allows the user to guess until they get the correct number. 我正在尝试创建一个程序,该程序创建一个随机数,并允许用户猜测,直到他们获得正确的数为止。 It serves no real purpose other than a learning experience for me. 除了对我的学习经历之外,它没有真正的目的。

I have the basic program working, I just want to add other elements to improve it and gain the experience. 我有基本程序正在运行,我只想添加其他元素来改进它并获得经验。

The program runs in a JFrame and has a JTextField for the user to enter their guess. 该程序在JFrame中运行,并具有JTextField供用户输入其猜测。 I have ActionListener setup for the JTextField. 我为JTextField设置了ActionListener。 I'd like to add a Start button that displays at the beginning of the game. 我想添加一个开始按钮,该按钮显示在游戏开始时。 When the user clicks the start button, the JTextField should become active. 当用户单击开始按钮时,JTextField应该变为活动状态。 Also, when the user clicks guesses the correct answer, I'd like to use the start button to reset the program. 另外,当用户单击时猜测正确的答案时,我想使用“开始”按钮来重置程序。 I've experimented with several ways to do this with no success. 我已经尝试了几种方法来完成此操作,但均未成功。 I believe this will require multiple ActionListeners in the same class. 我相信这将需要在同一类中使用多个ActionListeners。 I'm not even sure if this is possible? 我什至不确定这是否可行?

Here is my code. 这是我的代码。 Thanks in advance for any help. 在此先感谢您的帮助。

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class JMyFrame2 extends JFrame implements ActionListener {
    Random num = new Random();
    int computerGenerated = num.nextInt(1000);
    public int userSelection;
    JTextField numberField = new JTextField(10);
    JLabel label1 = new JLabel();
    Container con = getContentPane();
    int previousGuess;

    // constructor for JMyFrame
    public JMyFrame2(String title) {
        super(title);
        setSize(750, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label1 = new JLabel(
                "I have a number between 1 and 1000 can you guess my number?" + "Please enter a number for your first guess and then hit Enter.");

        setLayout(new FlowLayout());
        add(numberField);
        add(label1);
        System.out.println(computerGenerated);

        numberField.addActionListener(this);
    }


    public void actionPerformed(ActionEvent e) {
        userSelection = Integer.parseInt(numberField.getText());
        con.setBackground(Color.red);

        if (userSelection == computerGenerated) {
            label1.setText("You are correct");
            con.setBackground(Color.GREEN);
        } else if (userSelection > computerGenerated) {
            label1.setText("You are too high");
        } else if (userSelection < computerGenerated) {
            label1.setText("You are too low");
        }
    }
}


public class JavaProgram5 {

    public static void main(String[] args) {


        JMyFrame2 frame2 = new JMyFrame2("Assignment 5 - Number Guessing Game");
        frame2.setVisible(true);
    }
}

Sure you can have multiple action listeners. 确保您可以有多个动作侦听器。 In fact, your class should not implement it. 实际上,您的班级不应实现它。

Start by removing the actionPerformed method, and replace this line: 首先删除actionPerformed方法,然后替换以下行:

  numberField.addActionListener(this); 

With this: 有了这个:

    numberField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            userSelection = Integer.parseInt(numberField.getText());
            con.setBackground(Color.red);

            if (userSelection == computerGenerated) {
                label1.setText("You are correct");
                con.setBackground(Color.GREEN);
            } else if (userSelection > computerGenerated) {
                label1.setText("You are too high");
            } else if (userSelection < computerGenerated) {
                label1.setText("You are too low");
            }
        }
    });

You can add another action listener to the start button you plan to add, following this pattern, using an anonymous class. 您可以按照此模式,使用匿名类将另一个动作侦听器添加到计划添加的开始按钮。 (It doesn't have to be an anonymous class, this was just simple to demonstrate.) (它不必是一个匿名类,这只是简单演示。)

As janos said, adding an action listener to each button does the job well, but in large code when you need to add a lot of buttons it doesn't look too neat, I suggest you using the setActionCommand() for the JButton s that you are creating, the usage is simple, you implement ActionListener to the JFrame as you did but after each button add 正如janos所说,向每个按钮添加一个动作侦听器可以很好地完成这项工作,但是在大型代码中,当您需要添加许多按钮时,它看起来并不太整洁,我建议您将setActionCommand()用于JButton ,您正在创建,用法很简单,您就像在JFrame实现ActionListener一样,但是在添加每个按钮之后

button.addActionListener(this);
button.setActionCommand("commandname")

And you can do it for as much as buttons as you wish, now to fire these commands correctly your action performed function should look like this: 您可以根据需要按任意数量的按钮执行操作,现在正确触发这些命令,您执行的操作应如下所示:

@Override
public void actionPerformed (ActionEvent e) {
String cmd = e.getActionCommand();
switch(cmd) {
    case "action1":
        // Do something
        break;
    case "action2":
        // Do something else
        break;
    case "potato":
        // Give Mr. chips a high five
        break;
    default:
        // Handle other cases
        break;
    }
}

And so on, again the other solution works perfectly fine, I just personally think that this one is a lot neater especially in a code where you have multiple action listeners. 依此类推,另一种解决方案也可以很好地工作,我个人认为这很整洁,尤其是在具有多个动作侦听器的代码中。

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

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