import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class Question extends JFrame{
Random random = new Random();
private int number1 = random.nextInt(10) + 1;
private int number2 = random.nextInt(10) + 1;
private JTextField textField ; //注意此处声明了 textField
public Question(){
super("Question");
setLayout(new FlowLayout() );
JLabel integer1 = new JLabel( String.valueOf(number1) );
add(integer1);
JLabel addition = new JLabel(" + ");
add(addition);
JLabel integer2 = new JLabel( String.valueOf(number2) );
add(integer2);
JLabel equal = new JLabel(" = ");
add(equal);
JTextField textField= new JTextField(5); /** 注意此处再次声明了 textField 这时两个textField(类中与构造函数中)的指向是不同的,这将导致语句if (arg0.getSource() == textField) 永远为非,因为这里的textField是构造函数中的引用,正确的写法应该是textField= new JTextField(5);*/
add(textField);
action handler = new action();
textField.addActionListener(handler);
}
private class action implements ActionListener
{
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getSource() == textField)
{
if (Integer.parseInt( arg0.getActionCommand() ) == (number1 + number2) )
{
JOptionPane.showMessageDialog(null, "Correct");
}
else
JOptionPane.showMessageDialog(null, "Correct Answer is: "
+ ( number1 + number2 ) );
}
// JOptionPane.showMessageDialog(null, "Correct Answer is: "
// + ( number1 + number2 ) );
}
}
public static void main (String argc[])
{
Question test = new Question();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(170,75);
test.setVisible(true);
}
}
非常难察觉的声明引用指向错误
最新推荐文章于 2022-05-12 19:40:00 发布