【发布时间】:2014-04-10 02:05:55
【问题描述】:
问题字段应包含 36 个问题,这些问题的答案位于网格中的 36 个按钮上。
当用户选择点击正确的按钮回答按钮被取消网格时,目的是清除网格,使网格为空。
如果用户点击了错误的按钮,游戏会重新开始。
我在添加问题标签时遇到问题。
当用户点击正确的按钮时,问题字段应显示 36 个问题,从 0 + 1 开始 问题 2 在字段中显示 1+1 等到问题 36
我试图通过更改这行代码来实现这一点
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
到这里:
gui.statusLabel.setText("what is " + gui.buttonCounter + "+ 1");
但是虽然选择了正确的答案,但游戏无法正常运行,代码一直说在此代码中执行“else”,即。单击了错误的按钮,重新开始:0+ 1 是什么
if(clickedNumber == gui.buttonCounter){
gui.buttonCounter++;
buttonClicked.setText("");//optional - clears correct selection
if(gui.buttonCounter > gui.ROWS*gui.COLUMNS) gui.reset();
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
} else {
gui.reset();
gui.statusLabel.setText("Incorrect button clicked, start again: what is 0+ 1");
}
}
}
我该如何解决这个问题?所以当我点击正确答案按钮时,它会移动到下一个问题并且不显示点击了不正确的按钮,重新开始:什么是 0+ 1。
完整代码
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS * COLUMNS];
JLabel statusLabel = new JLabel("", JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS, COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x + 1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel, BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset() {
Collections.shuffle(buttonNumbers);
for (int x = 0, y = ROWS * COLUMNS; x < y; x++) {
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 1;
statusLabel.setText("Please click button " + buttonCounter);
}
public static void main(String[] args) {
new NewClass();
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g) {
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton) e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
if (clickedNumber == gui.buttonCounter) {
gui.buttonCounter++;
buttonClicked.setText("");// optional - clears correct selection
if (gui.buttonCounter > gui.ROWS * gui.COLUMNS)
gui.reset();
// gui.statusLabel.setText("Please click button" +
// gui.buttonCounter);
gui.statusLabel.setText("what is " + buttonCounter);
} else {
gui.reset();
gui.statusLabel
.setText("Incorrect button clicked, start again: 0 + 1");
}
}
}
}
【问题讨论】:
-
如果问题是“什么是[按钮计数器] + 1”,为什么条件是 clickedNumber == [按钮计数器]?不会是 clickedNumber == [按钮计数器] + 1 吗?
-
在
actionPerformed方法中添加断点并调试它... -
我正在添加完整的代码。我确实更改了您的建议,但仍然出现相同的错误。
-
您确定 clickedNumber 和 gui.buttonCounter 是您的想法吗?您是否按照建议进行了调试?