我写了一个 GUI 程序,但我不确定我做错了什么。当我运行该程序时,它几乎立即退出。希望能帮到你,程序如下:
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);
}
}
(不要担心进口,我只是没有包括它们)任何帮助将不胜感激。