Java JTextComponent setTextComponetIntegerValid(final JTextComponent c)

Here you can find the source of setTextComponetIntegerValid(final JTextComponent c)

Description

Set the text component in which only numerics (positive decimal integers with character 0-9).

License

Open Source License

Parameter

Parameter Description
c the specified text component

Declaration

public static void setTextComponetIntegerValid(final JTextComponent c) 

Method Source Code

//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 {
    /**/*from  w w  w . ja v a 2s  . c  om*/
     * 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();
                    }
            }
        });
    }
}

Related

  1. setText(JTextComponent textComp, String text)
  2. setTextComponentMargins(JTextComponent component)
  3. setTextComponentTransparent( JTextComponent paramJTextComponent)
  4. setTextComponentTransparent( JTextComponent textComponent)
  5. setTextComponentTransparent( JTextComponent textComponent)
  6. setTextStyle(JTextComponent txt)
  7. setWarningBackground(JTextComponent comp)
  8. textComponentAsLabel(JTextComponent textcomponent)
  9. value(JTextComponent txt)