packageer;importjava.awt.BorderLayout;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjavax.swing.JTextField;importjavax.swing.SwingUtilities;importjavax.swing.WindowConstants;public class TextFieldTest extendsjavax.swing.JFrame {privateJTextField field;/*** Auto-generated main method to display this JFrame*/
public static voidmain(String[] args) {
SwingUtilities.invokeLater(newRunnable() {public voidrun() {
TextFieldTest inst= newTextFieldTest();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}publicTextFieldTest() {super();
initGUI();
}private voidinitGUI() {try{
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
field= newLimitedTextField();
getContentPane().add(field, BorderLayout.CENTER);
}
pack();this.setSize(400, 70);
}catch(Exception e) {
e.printStackTrace();
}
}class LimitedTextField extendsJTextField {private int maxLength = 5;public void setMaxLength(intmaxLength) {this.maxLength =maxLength;
}public intgetMaxLength() {return this.maxLength;
}publicLimitedTextField() {this.addKeyListener(newKeyAdapter() {public voidkeyTyped(KeyEvent e) {int code =e.getKeyChar();if (code ==KeyEvent.VK_BACK_SPACE) {
e.isActionKey();
}else if (getDocument().getLength() >=maxLength) {
e.consume();
}
}
});
}
}
}