1

I'm doing a assignment on Java Swing and I'm making a GUI Guessing Game program. My question is when I press the "guess" button nothing happens, I can't close it by clicking X I have to terminate it with Eclipse. What did I do wrong? Is the GuessHandler correct implementing ActionListener or did I do something wrong there?

public class GuessingGameGui extends JFrame
{
    public static final int WIDTH = 600;
    public static final int HEIGHT = 400;
    private JTextField theText;
    private JLabel message;
    private JPanel p1;
    private JPanel p2;
    private int guess;
    private int numberOfTries = 0;

    public GuessingGameGui()
    {
        super();
        setSize(WIDTH, HEIGHT);
        //set the window title to "Guessing Game"
        setTitle("Guessing Game");
        Container c = getContentPane();
        c.setLayout(new BorderLayout( ));
        c.setBackground(Color.WHITE);

        p1 = new JPanel();
        p2 = new JPanel();

        p1.setBackground(Color.WHITE);
        p2.setBackground(Color.BLUE);

        //"add a JButton called "Guess"
        JButton guessButton = new JButton("Guess");
        GuessHandler ghandler = new GuessHandler();
        guessButton.addActionListener(ghandler);
        p1.add(guessButton);

        //The north panel will have a JLabel with the text "Guess a number between 1 and 10?"
        JLabel label1 = new JLabel("Guess a number between 1 and 10?");
        c.add(label1, BorderLayout.NORTH);

        //The south panel will have a JLabel for displaying if the user guessed correctly or not 
        message = new JLabel("");
        p2.add(message, BorderLayout.SOUTH);
        c.add(p2, BorderLayout.SOUTH);


        JPanel textPanel = new JPanel( );
        textPanel.setBackground(Color.LIGHT_GRAY);

        //In the center panel, add a JTextField where the user can enter a number to guess
        theText = new JTextField(10);
        theText.setBackground(Color.WHITE);
        textPanel.add(theText);
        textPanel.add(p1);
        c.add(textPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args)
    {
        GuessingGameGui guessGame = new GuessingGameGui();
        guessGame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        guessGame.setSize(WIDTH, HEIGHT);
        guessGame.setVisible(true);
    }

    class GuessHandler implements ActionListener {
        @Override
        public void actionPerformed( ActionEvent e )
        {
            int numberToGuess = (int) (Math.random() * 10 + 1);
            Scanner input = new Scanner (System.in);
            boolean win = false;
            while (win == false){

                guess = input.nextInt();
                numberOfTries++;
                if (guess < 1 || guess > 10)
                {
                    //Make the south panel background color RED if they entered an invalid number (not between 1 and 10)
                    p2.setBackground(Color.RED);
                }
                else if (guess == numberToGuess)
                {
                    win = true;
                    //Make the south panel background color YELLOW if they guessed right
                    p2.setBackground(Color.YELLOW);
                    //and display "YOU GOT IT (n attempts)", where n is the number of attempts the user guessed
                    message.setText("YOU GOT IT (" +numberOfTries + "attempts)");
                }
                else
                {
                    //Make the south panel background color GREY if they guessed wrong
                    p2.setBackground(Color.GRAY);
                    //display "Sorry try again"
                    message.setText("Sorry try again");
                }
            }
        }
    }
}
Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
Mario H
  • 13
  • 5
  • Since your program is locking I think you have an infinite loop in your actionhandler so win is never set to true. Also you're getting input from the console not from the JTextfield you want – Arachnid Hivemind May 18 '16 at 13:50

2 Answers2

3

There are several issues in your program that cause your problem:

  1. You should not have a while loop in your method actionPerformed because otherwise your swing application will freeze.
  2. You don't need a Scanner as the guess is the value to extract from your text field such that guess = input.nextInt() should be guess = Integer.parseInt(theText.getText()). Indeed otherwise your application will freeze until an integer will be provided in the standard input stream which is not what you expect here.
Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
  • This is exactly it. Both points kill your application: The while loop will go on indefinitely without ever being able to respond to new input. And the Scanner will simply block forever waiting for console input. – Carl-Eric Menzel May 18 '16 at 14:22
0

It can be useful to always add this to your frame:

 frame.setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
 frame.addWindowListener( new WindowAdapter() {
    @Override
    public void windowClosing( final WindowEvent e ) {
        handleExitRequest();
    }
 } );

and then create a method handleExitRequest() to do the actual close (perhaps just calling System.exit(0);) You also call that method from the actionPerformed() of an "Exit" menu item, if you have such. This allows you to clean up anything that should be done before exiting (say commit or rollback any database operations, etc.)

FredK
  • 4,036
  • 1
  • 6
  • 11