简体   繁体   English

GuessGame无法获取程序来输出消息

[英]GuessGame can't get program to output messages

I got the widow and the buttons into the GUI but for the life of me I can't get anything to output. 我将寡妇和按钮插入了GUI,但是对于我一生来说,我什么也无法输出。 I am suppose to enter a guess, and from a random number the game generates. 我想输入一个猜测,然后根据一个随机数生成游戏。 It is suppose to tell me if I'm too high, too low or correct. 可以告诉我我是否太高,太低或正确。 Also, if it is not correct it's supposed to tell me if I am warm or cold. 另外,如果不正确,应该告诉我我是冷还是热。 If any one could point me in the right direction on this I would be grateful. 如果有人能指出我正确的方向,我将不胜感激。 I don't know what I'm doing wrong on this. 我不知道我在做什么错。 I have researched different topics but with the different ways to solve this problem none match what I was looking for. 我研究了不同的主题,但是用不同的方法来解决此问题,这些都不符合我的期望。

Here's the code: 这是代码:

//all necessary imports

public class GuessGame extends JFrame 
{
    private static final long serialVersionUID = 1L;
    private JFrame mainFrame;
    private JTextField guessField;
    private JLabel message1;
    private JLabel message2;
    private JLabel message3;
    private JLabel message4;
    private JLabel guessLabel;
    private JLabel tooHigh;
    private JLabel tooLow;
    private JButton guessButton;
    private JButton newGame;
    private JButton exitButton;
    private int randomNum = 0;
    private final int MAX_NUM = 1000;
    private final int MIN_NUM = 1;
    private int guessCount;
    private int lastDistance;

    public GuessGame()
    {
        mainFrame = new JFrame();
        guessField = new JTextField(4);
        message4 = new JLabel("I have a number between 1 and 1000 -- can you guess my number?") ;
        guessLabel = new JLabel("Please Enter Your Guess:");


        guessButton = new JButton("Guess");
        newGame = new JButton("New Game");
        exitButton = new JButton("Exit");

        Container c = mainFrame.getContentPane();
        c.setLayout(new FlowLayout());
        c.setBackground(Color.CYAN);

        c.add(message4);
        c.add(guessLabel);
        c.add(guessField);
        c.add(guessButton);
        c.add(newGame);
        c.add(exitButton);

        newGame.setMnemonic('N');
        exitButton.setMnemonic('E');
        guessButton.setMnemonic('G');

        mainFrame.setSize(420, 300);//Sets width and height of Window
        mainFrame.setVisible(true);//Allows GUI to be visible
        mainFrame.addWindowListener(new WindowAdapter()

        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });

        GuessButtonsHandler gHandler = new GuessButtonsHandler();
        guessField.addActionListener(gHandler);

        ExitButtonsHandler eHandler = new ExitButtonsHandler();
        exitButton.addActionListener(eHandler);

        NewGameButtonsHandler nHandler = new NewGameButtonsHandler();
        newGame.addActionListener(nHandler);
    }

    class GuessButtonsHandler implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {

            Random rand = new Random();

            int guess = 0;
            int currDistance = 0;
            boolean correct = false;
            guess = Integer.parseInt(guessField.getText());//Converts String to Integer

            if(guessCount == 0)
            {
                lastDistance = MAX_NUM;
            }

            if(guess >= MIN_NUM && guess <= MAX_NUM)
            {
                guessCount += 1;
            }

            if(guess > randomNum)
            {
                 tooHigh.setText("Number To High!!!");
                 guessCount += 1;
            }

            else if(guess > randomNum)
            {
                 tooLow.setText("Number To Low!!!");
                 guessCount += 1;
            }

            else 
            {
                correct = true;
                message2.setText("Correct!!!");
                message2.setBackground(Color.GREEN);
                guessField.setEditable(false);
            }

            if(!correct)
            {
                currDistance = Math.abs(guess - randomNum);
            }

            if(currDistance <= lastDistance)
            {
                message3.setText("You are getting warmer!!!");
                mainFrame.add(message3).setBackground(Color.RED);

            }

            else
            {
                message4.setText("You are getting colder!!!");
                mainFrame.add(message4).setBackground(Color.BLUE);
            }

                lastDistance = currDistance;
                randomNum = rand.nextInt(1000) + 1;
        }

    }

    class NewGameButtonsHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            Random rand = new Random();
            randomNum = rand.nextInt(1000) + 1;
            guessCount = 0;
        }
    }

    class ExitButtonsHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
}

public class GuessGameTest {

    public static void main(String[] args) 
    {
        new GuessGame();
    }
}

You need to: 你需要:

  1. Add gHandler as a listener to the button too, not only to the text field: 也将gHandler作为侦听器添加到按钮,而不仅仅是文本字段:

     guessField.addActionListener(gHandler); guessButton.addActionListener(gHandler); 

    Keeping it in the text field too is a good idea: then the guess can be triggered by pressing enter too, not just clicking the button (this part actually works in your code). 也将其保存在文本字段中是个好主意:然后也可以通过按Enter键来触发猜测,而不仅仅是单击按钮(此部分实际上在您的代码中起作用)。

  2. You need to initialize the message labels, and add them somewhere. 您需要初始化消息标签,并将其添加到某处。 You have additions commented out, but the initializations are missing. 您已注释掉其他添加项,但是缺少初始化。

  3. You don't really need labels for all possible messages. 您实际上并不需要所有可能消息的标签。 You want to display only a message for too high, too low, or correct guess at a time. 您只想一次显示太高,太低或正确猜测的消息。 Not two or more simultaneously. 不能同时两个或多个。 So one field is enough, just set the correct text. 因此,一个字段就足够了,只需设置正确的文本即可。

  4. You have the condition inverted when checking too low numbers. 当检查太低的数字时,您将条件倒转。

  5. You generate a new random number after each guess, so the "getting warmer" messages are not very useful. 您在每次猜测后都会生成一个新的随机数,因此“变暖”消息不是很有用。 Also you don't need to create a new Random object every time you want a new random number. 同样,您不需要每次想要新的随机数时都创建一个新的Random对象。

Possibly others too, but hopefully these help you forward. 可能也有其他人,但希望这些可以帮助您前进。

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

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