我有這樣的代碼,在一個JTextField是「禁用」用戶輸入後n個字符插入:塊文字書寫後n個字符
JTextField tf = new JTextField();
tf.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (((JTextField) e.getSource()).getText().length() > n) {
e.consume();
}
}
});
它的工作原理,但我想知道如果有一個選擇,因爲我在一臺舊的慢速電腦上試了一次,當我在文本框中輸入某些東西時,信件被添加了,然後它消失了......我想避免在用戶輸入後使用e.consume()
,並直接阻止插入。
可能嗎?
編輯
我忘了提,我只是在這個例子中使用JTextField
,但我想這個代碼與普通的文本輸入組件的工作像JTextPane
,JTextArea
等
這可能幫助:http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters- in-jtextfield –
看起來像documentFilter是所有這些情況下的方式。 JTextPane支持文檔,至於JTextArea:http://www.linuxquestions.org/questions/programming-9/java-jtextarea-limiting-amount-of-characters-entered-155469/#post805335 –
任何實現JTextComponent '界面有一個文件。如果特定文檔支持setDocumentFilter(例如'AbstractDocument'),則可以使用此方法。 http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html。 –