【发布时间】:2015-04-08 17:48:35
【问题描述】:
我正在尝试制作一个游戏,在上述游戏中,有 21 根棍子,每个人轮流拿 1-4 根棍子,直到没有棍子,如果你不能再拿棍子,你就输了。我已经在 Eclipse 中成功制作了这个程序,但现在我想向它添加 GUI,所以我必须更改代码。此代码不完整,但每当我按下作为我的 actionListener 的 Go 按钮时它就会崩溃。我会在文本字段中输入一个数字,然后按 go,它就会崩溃。我该如何解决这个问题?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sticks extends JFrame {
JButton Go;
JTextField tf1, tf2;
static JTextField sttf;
JLabel startTake;
static JLabel errorTake;
JLabel uTake;
JLabel compTake;
public Sticks() {
setLayout(new GridLayout(5, 2, 5, 5));
startTake = new JLabel("How many sticks do you want to take? (1-4)");
add(startTake);
sttf = new JTextField();
add(sttf);
errorTake = new JLabel("Hello");
add(errorTake);
Go = new JButton("Go");
add(Go);
uTake = new JLabel("");
add(uTake);
compTake = new JLabel("");
add(compTake);
// tf1 = new JTextField();
// add(tf1);
// TakeP = new JLabel("One stick taken");
// add(TakeP);
event e = new event();
Go.addActionListener(e);
}
public static class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
int numSticks = 21;
int numToTake = 0;
int randomNum = 0;
while (numSticks > 0) {
try {
int num = (int) (Double.parseDouble(sttf.getText()));
int NumSticks = numSticks - num;
errorTake.setText("There are: " + numSticks + " left");
Robot Rob = new Robot();
numToTake = (int)Math.random() * 4 + 1;
errorTake.setText("There are: " + numSticks + " left");
}
catch (Exception ex) {
ex.printStackTrace();;errorTake.setText("There is a problem");
}
}
}
}
public static void main(String[] args) {
Sticks gui = new Sticks();
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 200);
gui.setTitle("Nice Game");
}
}
【问题讨论】:
-
把
catch (Exception exx) { errorTake.setText("Numbers only!");改成catch (Exception exx) { exx.printStackTrace(); errorTake.setText("Numbers only!");然后复制/粘贴异常输出。 -
我没有得到堆栈跟踪
标签: java eclipse swing user-interface crash