JTextField: How to limit the number of characters?

前端 未结 2 1436
时光说笑
时光说笑 2021-01-12 18:01

Please have a look at the following code.

import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.text.AbstractDocum         


        
相关标签:
2条回答
  • 2021-01-12 18:24

    You should make your own class that checks whether you gave more input than the maximum allowed length: See an example on http://www.java2s.com/Tutorial/Java/0240__Swing/LimitJTextFieldinputtoamaximumlength.htm.

    0 讨论(0)
  • 2021-01-12 18:35

    simply change your current remove method:

     @Override  
     public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException 
     {  
    
         fb.insertString(offset, "", null);
     } 
    

    for this one:

     @Override  
     public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException 
     {  
         fb.remove(offset, length);
     }
    

    it should now work.

    0 讨论(0)
提交回复
热议问题