I was just starting to learn the Java GUI and ran into this problem during event handling. Here is the initial window
When I enter a number inside the text box, it should say whether the guessed number is higher, lower, or matches. If it does not match, it requests a different number. But the window just freezes . After entering data
I guess it gets into an infinite loop. Here is the code. Help me figure out where the problem is. Thanks.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RandomNumGame extends JFrame { private JLabel promptLabel, resultLabel, answerLabel; private int tries=1, randomNum, guessNum; private JButton button; private JTextField txt; private boolean guessed; public RandomNumGame() { setLayout(new FlowLayout()); promptLabel = new JLabel("Guess a number(1-1000): "); add(promptLabel); txt = new JTextField(7); add(txt); button = new JButton("Guess!"); add(button); resultLabel = new JLabel(""); add(resultLabel); Event e = new Event(); button.addActionListener(e); } private class Event implements ActionListener{ public void actionPerformed(ActionEvent e){ randomNum = (int )(Math.random() * 1000 + 1); guessed=false; do{ try{ guessNum = (int)(Double.parseDouble(txt.getText())); if(guessNum>randomNum){ resultLabel.setText("Your number is higher. Try Again"); } else if(guessNum<randomNum){ resultLabel.setText("Your number is lower. Try Again"); } else{ resultLabel.setText("Your number matched!"); guessed=true; } } catch(Exception ee){ resultLabel.setText("Enter a legit number. What are you stupid?"); } }while(!guessed); } } public static void main(String[] args) {
source share