Java tutorial
//package com.java2s; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.text.JTextComponent; public class Main { /** * Set the text component in which only numerics (positive decimal integers * with character 0-9). * * @param c * the specified text component */ public static void setTextComponetIntegerValid(final JTextComponent c) { c.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() != KeyEvent.VK_BACK_SPACE) try { Integer.valueOf(c.getText() + e.getKeyChar()); } catch (NumberFormatException nfe) { e.consume(); Toolkit.getDefaultToolkit().beep(); } } }); } }