使用Thread.sleep()时,JTextField.setText()出现问题。这是我正在制作的基本计算器。当输入字段中的输入格式不正确时,我希望“输入错误”出现在输出字段中5秒钟,然后将其清除。当我将文本一次设置为“INPUT ERROR”(输入错误)时,setText()方法_确实_起作用,并且通过打印之间的文本,我发现它确实可以与setText(“”)一起使用。当我将Thread.sleep()放在它们之间时,就会出现问题。这是代码的SSCCE版本:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.regex.Pattern; import javax.swing.*; public class Calc { static Calc calc = new Calc(); public static void main(String args[]) { GUI gui = calc.new GUI(); } public class GUI implements ActionListener { private JButton equals; private JTextField inputField, outputField; public GUI() { createFrame(); } public void createFrame() { JFrame baseFrame = new JFrame("Calculator"); baseFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = new JPanel(); BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS); contentPane.setLayout(layout); baseFrame.setContentPane(contentPane); baseFrame.setSize(320, 100); equals = new JButton("="); equals.addActionListener(this); inputField = new JTextField(16); inputField.setHorizontalAlignment(JTextField.TRAILING); outputField = new JTextField(16); outputField.setHorizontalAlignment(JTextField.TRAILING); outputField.setEditable(false); contentPane.add(inputField); contentPane.add(outputField); contentPane.add(equals); contentPane.getRootPane().setDefaultButton(equals); baseFrame.setResizable(false); baseFrame.setLocation(100, 100); baseFrame.setVisible(true); } /** * When an action event takes place, the source is identified and the * appropriate action is taken. */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == equals) { inputField.setText(inputField.getText().replaceAll("\\s", "")); String text = inputField.getText(); System.out.println(text); Pattern equationPattern = Pattern.compile("[\\d(][\\d-+*/()]+[)\\d]"); boolean match = equationPattern.matcher(text).matches(); System.out.println(match); if (match) { // Another class calculates } else { try { outputField.setText("INPUT ERROR"); // This doesn't appear Thread.sleep(5000); outputField.setText(""); } catch (InterruptedException e1) { } } } } } }
我实际上不是在使用嵌套类,但我希望它能够为您包含在一个类中。很抱歉,GUI的外观如何,但这又是为了减少代码。重要部分(if (e.getSource()== equals))与我的代码保持不变。输入错误的最简单方法是使用字母。
if (e.getSource()== equals)
使用时,Thread.sleep()您正在主线程上执行此操作。这会将gui冻结5秒钟,然后更新outputField。发生这种情况时,它将使用最后设置的文本,该文本为空白。
Thread.sleep()
outputField
使用Swing计时器要好得多,下面的示例可以完成您要完成的任务:
if (match) { // Another class calculates } else { outputField.setText("INPUT ERROR"); ActionListener listener = new ActionListener(){ public void actionPerformed(ActionEvent event){ outputField.setText(""); } }; Timer timer = new Timer(5000, listener); timer.setRepeats(false); timer.start(); }