[英]Jtextfield and keylistener
我有一個jtextfield(jt),我想要在其中例如用戶在其中鍵入"e"
將單詞"Example"
自動寫入jtextfield中。
我使用代碼:
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);
}
}
}
您可以移動jt.setText("Example");
進入KeyListener
的public void keyReleased(KeyEvent e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.