I’ve written a GUI program and I’m not sure what I’m doing wrong. When I run the program, it just quits almost instantly. Hope you can help, here’s the program:
public class RandomGame extends JFrame {
private JTextField t1 = new JTextField();
private double t1num = Double.parseDouble(t1.getText());
public RandomGame() {
setLayout(new FlowLayout());
Event1 e1 = new Event1();
t1.addKeyListener(e1);
add(t1);
}
public class Event1 implements KeyListener {
@Override
public void keyPressed(KeyEvent arg0) {
Random r = new Random();
switch (arg0.getKeyCode()) {
case KeyEvent.VK_ENTER:
if(t1num == r.nextInt()) {
t1.setText("You Won!");
}
else {
t1.setText("You Lost.");
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
RandomGame gui = new RandomGame();
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
gui.setSize(1280, 800);
gui.setTitle("Random Game");
gui.setVisible(true);
}
}
(Don’t worry about the imports, I just haven’t included them)
Any help would be appreciated.
A
NumberFormatExceptionis thrown on startup on this line:as the
JTextFieldt1will contain an emptyString.In fact, this can be simply left unassigned and will take the default
0value used for numeric primitives.Additionally when using
Randomcould be written as:
Also
KeyListeneris not recommended for use withJTextComponents. Here you simply require the ENTER key action to be handled so anActionListenerwould be better & simpler to use.