Используйте DocumentFilter
. Затем вы можете настроить фильтр для вашего конкретного c требования.
Базовый пример c, чтобы начать:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class DigitFilter extends DocumentFilter
{
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributes)
throws BadLocationException
{
replace(fb, offset, 0, text, attributes);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attributes)
throws BadLocationException
{
Document doc = fb.getDocument();
// add check here check the length of the text currently in the document
// with the length of your text String to make sure the total is not above the maximum
// you should modify the class to pass a paramenter when you create the class for the
// maximum length so the class can be reused
if (isDigit( text ))
super.replace(fb, offset, length, text, attributes);
else
Toolkit.getDefaultToolkit().beep();
}
private boolean isDigit(String text)
{
for (int i = 0; i < text.length(); i++)
{
if (! Character.isDigit( text.charAt(i) ) )
return false;
}
return true;
}
private static void createAndShowGUI()
{
JTextField textField = new JTextField(15);
AbstractDocument doc = (AbstractDocument) textField.getDocument();
doc.setDocumentFilter( new DigitFilter() );
JFrame frame = new JFrame("Integer Filter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new java.awt.GridBagLayout() );
frame.add( textField );
frame.setSize(220, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
Вам нужно будет добавить отдельные логики c (внешний по отношению к DocumentFilter), чтобы убедиться, что длина учетной записи составляет не менее 8 цифр, прежде чем выполнять обработку.
Прочитайте раздел из учебника Swing по Внедрение фильтра документов для примера фильтра, который ограничивает количество символов. Логика c оттуда должна быть объединена с примером здесь.