当我在文本框中输入某些内容时,如果我按 Enter 键,我的应用程序就会卡住并停止响应。这是一个你尝试获取 1 到 100 之间的数字的游戏。我想我需要一个提交按钮或回车键上的 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 循环,一切正常。它这样做对吗?
最佳答案
你的问题就在这里,猜测
或数字
永远不会改变值,无限循环
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);
}
}
不需要的只需删除即可
所以你的内部类会是这样的
public class MyEvent implements ActionListener {
public void actionPerformed(ActionEvent a) {
int guess = 0;
try {
guess = Integer.parseInt(input.getText());
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("Right the number was "+number);
result.setForeground(Color.GREEN);
}
}catch(NumberFormatException nfe){
result.setText("Error - Illegal Data Entered");
result.setForeground(Color.RED);
}
}
}
当该整数失败时,我 try catch 所有 block 原因,您必须结束事件的执行..
注意遵循约定,声明性名称和类应以大写字母开头
关于Java Actionlistener 提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930557/