我使用关键侦听器从用户读取输入,但我有一个问题。首先,我给JTextField读了“请输入你的名字”。如果用户输入一个名称,例如John,它将更改为John。但是,如果用户输入无效字符,例如"7",我想写“请输入您的名字”,但是它会写“请输入您的name7"。它正在进行,直到给出一个正确的输入。我怎么纠正它们??
public void keyTyped(KeyEvent e) {
int ascii = (int)e.getKeyChar();
if((ascii >= 65 && ascii <=122) || (ascii <= 351 && ascii >= 199 )){
if(TextField1.getText().equals("Please enter your name"))
TextField1.setText("");
}
else
TextField1.setText("Please enter your name");
}发布于 2015-11-07 23:20:37
变量名不应以大写字符开头。
if((ascii >= 65 && ascii <=122) || (ascii <= 351 && ascii >= 199 )){别用神奇的数字。如果要检查小写字母或大写字母,请使用来自Character类的方法,如isLetter(...)。
不要使用KeyListener,这是一个旧的API。Swing有更新的更好的API。例如,如果将文本粘贴到文本字段,您的逻辑就无法工作。在输入文本时,使用JFormattedTextField或DocumentFilter检查有效数据。有关更多信息,请参见关于如何编写文档筛选器和如何使用文本字段的Swing教程中的部分。
我不建议在文本字段中放置文本作为提示符。要获得不同的方法,请查看文本提示
但是上面写着“请输入你的name7”。
之所以发生这种情况,是因为keyTyped事件是在用类型化文本更新文档之前生成的。要最后执行setText()方法,可以将该语句包装在SwingUtiltities.invokeLater(.)中。
基于上述所有原因,我不建议采用这种方法。
发布于 2015-11-07 23:07:19
不要将KeyListener与JTextComponent (如JTextArea )一起使用。相反,一种选择是使用添加到组件文档中的DocumentListener或DocumentFilter。如果要完全阻止用户输入无效字符,则DocumentFilter可以正常工作。另一个选项是将一个InputVerifier附加到当用户试图离开文本组件时启动的组件。
例如
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
import javax.swing.text.JTextComponent;
@SuppressWarnings("serial")
public class MyTextField extends JPanel {
private static final String DEFAULT_TEXT = "Please enter your name";
private static final int COLUMNS = 20;
private JTextField textField = new JTextField(DEFAULT_TEXT, COLUMNS);
public MyTextField() {
add(new JLabel("Name:"));
add(textField);
add(new JButton("Submit"));
textField.addFocusListener(new TextFocusListener());
textField.setInputVerifier(new MyInputVerfier());
}
private class TextFocusListener extends FocusAdapter {
@Override
public void focusGained(FocusEvent e) {
JTextComponent textComp = (JTextComponent) e.getComponent();
if (textComp != null) {
textComp.selectAll(); // so can change all text
}
super.focusGained(e);
}
}
private class MyInputVerfier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextComponent) input).getText();
if (!text.replaceAll("\\d", "").equals(text)) {
return false;
}
return true;
}
@Override
public boolean shouldYieldFocus(JComponent input) {
if (!verify(input)) {
JTextComponent textComp = (JTextComponent) input;
textComp.setText(DEFAULT_TEXT);
textComp.selectAll();
return false;
}
return super.shouldYieldFocus(input);
}
}
private static void createAndShowGui() {
MyTextField mainPanel = new MyTextField();
JFrame frame = new JFrame("MyTextField");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}https://stackoverflow.com/questions/33588825
复制相似问题