重複の可能性:
単一のスレッドに sleep() を使用する
Thread.sleep() を使用しているときに JTextField.setText() に問題があります。これは私が作っている基本的な電卓用です。入力フィールドへの入力が正しい形式ではない場合、出力フィールドに「INPUT ERROR」が 5 秒間表示されてからクリアされるようにします。setText() メソッドは、テキストを一度「INPUT ERROR」に設定しただけで機能し、その間にテキストを印刷することで、それと 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) {
}
}
}
}
}
}
私は実際にはネストされたクラスを使用していませんが、1 つのクラスに含めることができるようにしたかったのです。GUI の外観については申し訳ありませんが、これもコードを削減するためのものです。重要なセクション ( if (e.getSource() == equals)
) は、私のコードから変更されていません。間違った入力を行う最も簡単な方法は、文字を使用することです。