[英]Jtextfield and keylistener
I have a jtextfield (jt) where I want as soon as the user types "e"
for example in it, the word "Example"
to be written automatically in the jtextfield. 我有一个jtextfield(jt),我想要在其中例如用户在其中键入"e"
将单词"Example"
自动写入jtextfield中。
I use the code: 我使用代码:
KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
jt.setText("Example");
}
}
But this gives "Examplee"
when e is pressed! 但这在按下e时给出"Examplee"
! Any ideas? 有任何想法吗? Thanks a lot 非常感谢
Don't use KeyListener
on text components, there are a rafter of issues (not been notified, mutation exceptions, not been notified when the user pastes something into the field), instead, you should be using a DocumentFilter
请勿在文本组件上使用KeyListener
,否则会有很多问题(未通知,突变异常,当用户将某些内容粘贴到字段时未通知),而是应该使用DocumentFilter
For example... 例如...
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);
}
}
}
You can move your jt.setText("Example");
您可以移动jt.setText("Example");
into the public void keyReleased(KeyEvent e)
of your KeyListener
进入KeyListener
的public void keyReleased(KeyEvent e)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.