I'm having a problem with my assginment. This is the Java Number Guessing Game. It compiles and runs with no errors but when executed it stops with only one user input. You must hit the "Play Again" button to continue. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.event.*;
public class GuessNumber extends JApplet implements ActionListener{
private String titleStr="I have a number between 1 and 1000. Can you guess my number?";
private JLabel title=new JLabel(titleStr);
private JLabel ask=new JLabel("Please enter your first guess: ");
private JTextField guess=new JTextField();
private JLabel resultLabel=new JLabel("Result: ");
private JLabel result=new JLabel();
private JButton replay=new JButton("Play again");
Container cp=getContentPane();
private int randomNum;
public void init() {
randomNum=new Random().nextInt(1000)+1;
guess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str=e.getActionCommand();
try {
int guessNum=Integer.parseInt(str);
if (guessNum<randomNum) {
result.setText("Too Low");
guess.setBackground(Color.BLUE);
}
if (guessNum>randomNum) {
result.setText("Too High");
guess.setBackground(Color.RED);
}
if (guessNum==randomNum) {
result.setText("Correct!");
guess.setBackground(Color.WHITE);
guess.setEditable(false);
}
} catch (Exception ex) {
result.setText(ex.toString());
}
}
});
replay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
randomNum=new Random().nextInt(1000)+1;
guess.setEditable(true);
guess.setText("");
guess.setBackground(Color.WHITE);
result.setText("");
}
});
JPanel midScreen=new JPanel();
midScreen.setLayout(new GridLayout(2,2));
midScreen.add(ask); midScreen.add(guess);
midScreen.add(resultLabel); midScreen.add(result);
cp.setLayout(new FlowLayout());
cp.add(title);
cp.add(midScreen);
cp.add(replay);
}
public static void main(String[] args) {
JApplet applet = new GuessNumber();
JFrame frame = new JFrame("Guess my number");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().add(applet);
frame.setSize(400,150);
applet.init();
applet.start();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}