过去一周左右,我一直在自学 Java。我是编程新手。我的代码编译得很好,但小程序不显示任何文本字段,并且genRandomNumbers()
没有调用该方法。所以提示用户将两个数字相乘的问题不会显示在小程序上。
在我的代码中,genRandomNumber()
正在从init()
. 这会导致问题吗?我试图从 paint() 来做到这一点。这导致了更大的问题 - 小程序上没有显示任何文本字段。所以我把电话移genRandomNumber()
回init()
.
小程序窗口显示"Start: applet window not initialized"
在状态区域中。
你能指出我正确的方向吗?任何帮助是极大的赞赏!
这是我的代码:
//Generate 2 random numbers
//Post a question to multiply the two numbers
//Verify the answer entered
//Post a new question if the solution is correct
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class LearnMultiplication extends JApplet implements ActionListener
{
JLabel answerLabel;
JTextField answerTextField, commentTextField, questionTextField;
int random1, random2;
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout() );
JTextField questionTextField = new JTextField(30);
c.add(questionTextField);
JLabel answerLabel = new JLabel("Enter you answer here");
c.add(answerLabel);
JTextField answerTextField = new JTextField(5);
answerTextField.addActionListener(this);
c.add(answerTextField);
JTextField commentTextField = new JTextField(30);
c.add(commentTextField);
genRandomNumbers(); // invoke method to generate 2 random numbers
}
public void actionPerformed (ActionEvent e)
{
int a = Integer.parseInt(e.getActionCommand() );
verifyAnswer(a); // invoke method to verify the product
}
//method to generate 2 random numbers
public void genRandomNumbers()
{
random1= 1 + (int)(Math.random() * 9 );
random2 = 1 + (int)(Math.random() * 9 );
questionTextField.setText("Multiply " + Integer.toString(random1) + "and " + Integer.toString(random2) + ".");
}
// method to verify the product of the 2 random numbers
public void verifyAnswer(int answer)
{
int correctAnswer = random1 * random2;
if ( correctAnswer == answer)
{
commentTextField.setText("Very Good!");
genRandomNumbers(); //call the method again to generate 2 new random numbers
}
else
{
commentTextField.setText("No, try again!!");
}
}
}