我有一个 jtextfield (jt),我希望用户在其中键入 "e"
时,自动写入单词 "Example"
在 jtext 字段中。
我使用的代码:
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
jt.setText("Example");
}
}
但是当按下 e 时,这会给出“Examplee”
!有任何想法吗?非常感谢
最佳答案
不要在文本组件上使用KeyListener
,这会带来一系列问题(未收到通知、突变异常、用户将某些内容粘贴到字段中时未收到通知),相反,您应该使用 DocumentFilter
例如...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TextFieldExample {
public static void main(String[] args) {
new TextFieldExample();
}
public TextFieldExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
((AbstractDocument)field.getDocument()).setDocumentFilter(new ExampleExpandingDocumentFilter());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ExampleExpandingDocumentFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
System.out.println("I" + text);
super.insertString(fb, offset, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if ("e".equalsIgnoreCase(text)) {
text = "example";
}
super.replace(fb, offset, length, text, attrs);
}
}
}
关于java - Jtextfield 和 keylistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22954961/