我需要制作一个猜谜游戏程序。我想不出任何方法可以成功记录两个猜测以进行比较。我对“actionPerformed”方法遇到的问题最多。它没有链接到构造函数 - 就像 txtFld 和 Lbl3 一样,它表示它是一个空指针。这是我到目前为止所拥有的:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class GuessTheNumber extends JFrame
{
Random randNum = new Random();
int numToGuess = randNum.nextInt(1000);
int guess1;
int guess2;
public static void main(String [] args)
{
new GuessTheNumber();
} // end main
public GuessTheNumber()
{
setTitle("Guess The Number");
setLayout(new FlowLayout());
JLabel promptLbl1 = new JLabel("I have a number between 1 and 1000. Can you guess my number?");
add(promptLbl1);
JLabel promptLbl2 = new JLabel("Please enter your guess.");
add(promptLbl2);
JTextField txtFld = new JTextField(4);
add(txtFld);
JLabel Lbl3 = new JLabel();
add(Lbl3);
MyHandler handler = new MyHandler();
txtFld.addActionListener(handler);
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} //end constructor
private class MyHandler implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
String gs1;
guess1 = txtFld.getText();
guess1 = Integer.parseInt(gs1);
String gs2;
guess2 = txtFld.getText();
guess2 = Integer.parseInt(gs2);
if (gs1 > gs2)
txtFld.setBackground(color.blue);
else if (gs1 < gs2)
txtFld.setBackground(color.red);
if (gs2 == numToGuess)
{
Lbl3("Correct!");
txtFld.setBackground(color.green);
}
else if (gs2 > numToGuess)
Lbl3("Too High");
else if (gs2 < numToGuess)
Lbl3("Too Low");
} // end actionPerformed
} // end MyHandler
} // end GuessTheNumber
最佳答案
您必须将标签和文本字段的声明从构造函数移动到 GuessTheNumber。
public class GuessTheNumber extends JFrame
{
Random randNum = new Random();
int numToGuess = randNum.nextInt(1000);
int guess1;
int guess2;
JLabel promptLbl1;
JLabel promptLbl2;
JTextField txtFld;
JLabel Lbl3;
//...
public GuessTheNumber()
{
setTitle("Guess The Number");
setLayout(new FlowLayout());
promptLbl1 = new JLabel("I have a number between 1 and 1000. Can you guess my number?");
add(promptLbl1);
promptLbl2 = new JLabel("Please enter your guess.");
add(promptLbl2);
txtFld = new JTextField(4);
add(txtFld);
Lbl3 = new JLabel();
add(Lbl3);
//...
否则您只能在构造函数中访问它们。
关于java - 如何制作一个猜数字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306888/