importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.lang.Math;importjavax.swing.text.NumberFormatter;importjava.text.NumberFormat;publicclassJunglePart...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
import javax.swing.text.NumberFormatter;
import java.text.NumberFormat;
public class JungleParty extends JFrame implements ActionListener{
public static int correctAnswer = 10;
JLabel questionLabel = new JLabel("How many animals have come to the party?");
JPanel imagePanel = new JPanel();
JLabel[] imageLabel = new JLabel[10] ;
JPanel bottom = new JPanel();
JFormattedTextField textField;
/**
* This is a constructor of JungleFrame,
* used to create the window frame for application.
*/
public JungleParty(){
super("Welcome to the jungle party!");
setSize(750,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
/**
* This is a method to start displaying and asking.
* No argument and no return type here.
*/
public void ask(){
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(1);
formatter.setMaximum(10);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
textField = new JFormattedTextField(formatter);
textField.setColumns(2);
textField.setMaximumSize(textField.getPreferredSize());
textField.addActionListener(this);
JPanel askPanel = new JPanel();
askPanel.setLayout(new FlowLayout());
askPanel.add(questionLabel);
askPanel.add(textField);
addPic();
无关的
public void actionPerformed(ActionEvent e){
int userNumber = Integer.valueOf(textField.getText()).intValue();
if (userNumber != correctAnswer){//correct answer
questionLabel.setText("Wrong! Try again!");
textField.setText("");
}
else{
correctAnswer = (int)(Math.random()*10 + 1);
questionLabel.setText("Correct! How many animals are in the party now?");
textField.setText("");
imagePanel.removeAll();
for(int i = 0; i
imagePanel.add( imageLabel[i]);
}
imagePanel.repaint();
}
}
public static void main(String[] args){
JungleParty myParty = new JungleParty();
myParty.ask();
}
}
我明明在每次getText输入后都写了textField.setText("");
但是一旦输入了数字就再也清空不掉了???
为什么 很急。。求帮助
展开