Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Only numeric input in JTextField

Tue Oct 21, 2008 9:09 pm

Hi,

I'm trying to extend the JTextField class to a JNumField subclass in
which only numeric key-in would be accepted.
This is probably a very common problem, but I could not find a simple
solution to it yet.

I tried with a MaskFormatter, as explained here (see pjstroh's
message) but encountered problems when trying to compile the code.
Code:
http://forum.java.sun.com/thread.jspa?threadID=418002&messageID=1876495


So, I tried somehting different by checking the keyTyped key event.
But this does not work. Does someone know why ?

Here's some code from my JNumField class:
Code:
// *** Initialisation ***
public void init() {
setBackground(Color.white);
addKeyListener(this);
hasDecimalPoint = false;
}

// *** Impl�mentation de l'interface KeyListener ***
public void keyTyped(KeyEvent ke) {
char c = ke.getKeyChar();
if (!Character.isDigit(c))
ke.consume(); // prevent event propagation
}

Thanks for any help.



Re: Only numeric input in JTextField

Tue Oct 21, 2008 9:18 pm

Solved. The problem was that I adding the key listener from within the
init() function which is -I assume- called only for applets.
As my class is not an applet, the init() function was not called.
I can now catch key events as I moved addKeyListener(this) in the
class constructor.

Post a reply
  Related Posts  to : Only numeric input in JTextField
 Get Form Numeric value     -  
 input suggestion using Javascript     -  
 getting a full line input     -  
 Input-Output Operations     -  
 Read input from SWITCHES and PORTS     -  
 Google Chrome input file     -  
 Input username and password in JAVA     -  
 Read input from ports and print it on the LEDs     -  
 Input three numbers and then sort non descending order     -  
 Simple code for taking input from shell     -  

Topic Tags

Java Swing