我正在尝试重置我的 JTextField 以防输入 Space 。它抛出了我:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
我的代码是:
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class MainFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBackground(Color.LIGHT_GRAY);
desktopPane.setBounds(6, 6, 438, 266);
contentPane.add(desktopPane);
textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
if (textField.getText().contains(" ")) {
System.out
.println("Space was entered! clearing the text field");
textField.setText("");
}
}
});
textField.setBounds(133, 112, 134, 28);
desktopPane.add(textField);
textField.setColumns(10);
}
}