当我在文本框中输入内容时,如果我按 Enter 键,我的应用程序会冻结并停止响应。它是一个您尝试获取 1 到 100 之间的数字的游戏。我想我需要一个提交按钮或 Enter 键上的 ActionListener。有人可以帮我解决这个问题。还有一种方法可以在 FlowLayout 中换行吗?还是另一种布局更好?这是我的代码:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class game extends JFrame {
private static final long serialVersionUID = 1L;
private Random rand = new Random();
private int number = rand.nextInt(101);
private JLabel result, prompt;
private JTextField input;
game() {
super("Numbers");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
prompt = new JLabel("Enter a number between 1 and 100");
add(prompt);
input = new JTextField(3);
add(input);
result = new JLabel("");
add(result);
event a = new event();
input.addActionListener(a);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent a) {
int guess = 0;
try {
guess = Integer.parseInt(input.getText());
} catch(NumberFormatException e) {
result.setText("Error - Illegal Data Entered");
result.setForeground(Color.RED);
}
while(guess!=number) {
if(guess>number) {
result.setText("Guess Too High. Try Again.");
result.setForeground(Color.CYAN);
} else if(guess<number) {
result.setText("Guess Too Low. Try Again.");
result.setForeground(Color.CYAN);
} else {
result.setText("Unknown Error");
result.setForeground(Color.RED);
}
}
if(guess==number){
result.setText("Right the number was "+number);
result.setForeground(Color.GREEN);
}
}
}
public static void main(String[] args) {
new game().setVisible(true);
}
}
提前致谢。
更新
所以我删除了 While 循环,一切正常。它做对了吗?