Java Textfield ONLY NUMBERS

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 8058 Views - Last Post: 15 February 2013 - 08:06 PM Rate Topic: -----

#1 Buttertoast  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 10-January 13

Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 07:02 AM

Hey, i wanted to create a Textfield where it should only be possible to put numbers from 0-999 into.
Could anybody help me with this?
I already tried it with a formattedtextfield like this:
MaskFormatter formatter = new MaskFormatter("***");
formatter.setValidCharacters("0123456789");
tf = new JFormattedTextField(formatter);


but the problem was that if i wanted to put a number with less than 3characters( 10 for example) into it
i had to write (010) a zero in front of it and it wasnt possible to easily get the text out of this textfield.
does anyone have an idea?
this is the code to read out the textfield
public void keyReleased(KeyEvent e) {
                               if(e.getKeyCode()==KeyEvent.VK_ENTER || e.getKeyCode()==KeyEvent.VK_TAB){
                                   if (tf.getText()==null || ("".equals(tf.getText()))){
                                       tf.setText("0");
                                       geschwindigkeit2 = 0;
                                    }   
                                    else{

                                        int value = Integer.parseInt(tf.getText());
                                        if (value <100 && value > 9){
                                            tf.setText("0" + String.valueOf(value)); 
                                        }
                                        if (value<10){
                                         tf.setText("00" + String.valueOf(value)); 
                                        }
                                        geschwindigkeit2 = value;
                                    }
                                }   

                            }



Is This A Good Question/Topic? 0
  • +

Replies To: Java Textfield ONLY NUMBERS

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2689
  • View blog
  • Posts: 11,349
  • Joined: 20-September 08

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 07:07 AM

You can use a custom PlainDocument that will only accept numbers.
http://www.java2s.co...aindocument.htm
Was This Post Helpful? 0
  • +
  • -

#3 Buttertoast  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 10-January 13

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 07:13 AM

View Postg00se, on 14 February 2013 - 07:07 AM, said:

You can use a custom PlainDocument that will only accept numbers.
http://www.java2s.co...aindocument.htm

the link doesnt work somehow
Edit: nevermind, it works now

This post has been edited by Buttertoast: 14 February 2013 - 07:16 AM

Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2689
  • View blog
  • Posts: 11,349
  • Joined: 20-September 08

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 07:16 AM

Sorry. Try http://www.java2s.co...dfieldfield.htm instead. Change the ctor body to this(NUMERIC);

This post has been edited by g00se: 14 February 2013 - 07:19 AM
Reason for edit:: typo

Was This Post Helpful? 1
  • +
  • -

#5 Buttertoast  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 10-January 13

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 07:23 AM

View Postg00se, on 14 February 2013 - 07:16 AM, said:

Sorry. Try http://www.java2s.co...dfieldfield.htm instead. Change the ctor body to this(NUMERIC);

i tried this code but it is also possible to put characters into the textfield
€: Ah, works now, i only had to delete this line
public static final String ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


but i dont have to copy the whole code into my code,do i?

This post has been edited by Buttertoast: 14 February 2013 - 07:25 AM

Was This Post Helpful? 0
  • +
  • -

#6 Buttertoast  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 10-January 13

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 08:00 AM

ah, works perfectly now.
i only copied the class and changed a few lines adapted to my code, thank you very much :)
Was This Post Helpful? 0
  • +
  • -

#7 burakaltr  Icon User is online

  • D.I.C Regular

Reputation: 91
  • View blog
  • Posts: 274
  • Joined: 07-November 10

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 10:45 AM

You will need an approach like below

import java.util.Scanner;

public class Num {
	public static void main(String args[]){
		boolean cond=true;String i = "";
		Exception e2 = null;
		while(cond){
		try{
			System.out.println("Enter Digits ONLY !");
			i=new Scanner(System.in).next();
			for(int y=0;y<i.length();++y)if(!Character.isDigit(i.charAt(y)))throw   e2;;
			cond=false;
		}
		catch(Exception e){
			
			System.out.println(" ONLY DIGITS, PLEASE");
		}
		
	}
		System.out.println("Following is Only Numbers\n" + i);
	}
}

This post has been edited by burakaltr: 14 February 2013 - 10:46 AM

Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 01:43 PM

What is the idea of throwing an Exception and catching it in the same method ? This is useless, there is something you didn't get about Exception. You don't throw if you catch just after just execute the code in your catch() in the if that throws the Exc4eption.
Throwed Exception are to be catch by a method that called the method that throws.

I would add a DocumentListener to my JTextField
in the insertUpdate() method of the listener I'll check if the digit are number. If not I would simply remove them

That should do it


import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;

/*
 * A JTextField that only accept the number of digits it should 
 * (declared in the constructor) and accept only digits in it 
 */
public class NumericTextField extends JTextField implements DocumentListener {

	private static final long serialVersionUID = 201302141630L;
	private int nbColumns;
	private StringBuilder sb;

	NumericTextField(int nbColumns) {
		super(nbColumns);
		this.nbColumns = nbColumns;
		getDocument().addDocumentListener(this);
	}

	/*
	 * Make sure good length and numeric
	 */
	private void validateText() {

		String str = getText();
		System.out.println("Test is >" + str + "<");
		int len = str.length();
		// if nothing to do
		if(len == 0)
			return;	
		// if we will need to update the text
		boolean updateRequired = false;
		sb = new StringBuilder(nbColumns);

		// truncate if too long
		if(len > nbColumns) {
			str = str.substring(0, nbColumns);
			updateRequired = true;
			len = nbColumns;
		}
		// cumulate the valid digts in the StringBuiilder
		for(int i = 0; i < len; ++i) {
			char digit = str.charAt(i);
			if(digit >= '0' && digit <= '9')
				sb.append(digit);
			else
				updateRequired = true;   // flag at least one invalid digit
		}
		// if truncated or invalid digit found
		if(updateRequired) {
			
		    SwingUtilities.invokeLater(new Runnable() {
		        @Override
		        public void run() {
		            setText(sb.toString());
		        }
		    });
			
		}
	}
		

	@Override
	public void changedUpdate(DocumentEvent de) {
		validateText();
	}

	@Override
	public void insertUpdate(DocumentEvent de) {
		validateText();
	}

	@Override
	public void removeUpdate(DocumentEvent arg0) {
	}

	// to test the whole stuff
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.add(new NumericTextField(4), BorderLayout.NORTH);
		frame.add(new NumericTextField(8), BorderLayout.CENTER);
		frame.add(new NumericTextField(12), BorderLayout.SOUTH);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setVisible(true);
		frame.pack();
	}
}


This post has been edited by pbl: 14 February 2013 - 02:38 PM

Was This Post Helpful? 0
  • +
  • -

#9 burakaltr  Icon User is online

  • D.I.C Regular

Reputation: 91
  • View blog
  • Posts: 274
  • Joined: 07-November 10

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 06:07 PM

And what about this Mr. Pbl ?


import java.awt.Graphics;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Num extends JFrame implements InputMethodListener, KeyListener{
	JLabel lab=new JLabel("text");
	JTextField jt=new JTextField(60);

	Num(){	

		add(lab);add(jt);setVisible(true);
		jt.addKeyListener(this);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);
		setSize(200,200);pack();
	
		
	}
 	 
	
	public static void main(String args[]){
new Num();
}
	/*public void paint(Graphics g){
		
		super.paint(g);
	}*/

	public void caretPositionchanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void inputMethodTextChanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub
	
	}


	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
		boolean cond=true;String i = "";
		Exception e2 = null;
		
		while(cond){
		 {
			
			//System.out.println("Enter Digits ONLY !");
			//i=new Scanner(System.in).next();
			  i=String.valueOf(arg0.getKeyChar());
			for(int y=0;y<i.length();++y)if(!Character.isDigit(i.charAt(y)))arg0.consume();;
			cond=false;
		
		/*catch(Exception e){
			
			System.out.println(" ONLY DIGITS, PLEASE");
		}*/
		
		}
	}
		
	}


	@Override
	public void caretPositionchanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub
		
	}}

Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 09:09 PM

post correctly indented code and we'll see
You have to be masochist to write/post code like this

 for(int y=0;y<i.length();++y)if(!Character.isDigit(i.charAt(y)))arg0.consume();; 


This post has been edited by pbl: 14 February 2013 - 09:09 PM
Reason for edit:: This is candid camera or what ?

Was This Post Helpful? 0
  • +
  • -

#11 burakaltr  Icon User is online

  • D.I.C Regular

Reputation: 91
  • View blog
  • Posts: 274
  • Joined: 07-November 10

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 09:34 PM

if(!Character.isDigit(i.charAt(y))){

arg0.consume();

}




import java.awt.Graphics;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Num extends JFrame implements InputMethodListener, KeyListener{
	JLabel lab=new JLabel("text");
	JTextField jt=new JTextField(60);

	Num(){	

		add(lab);add(jt);setVisible(true);
		jt.addKeyListener(this);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);
		setSize(200,200);pack();


	}


	public static void main(String args[]){
		new Num();
	}
	/*public void paint(Graphics g){

		super.paint(g);
	}*/

	public void caretPositionchanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void inputMethodTextChanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub

	}


	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}


	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub

	}


	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub

		boolean cond=true;String i = "";
		Exception e2 = null;

		while(cond){
			{
 
				i=String.valueOf(arg0.getKeyChar());
				for(int y=0;y<i.length();++y)if(!Character.isDigit(i.charAt(y)))arg0.consume();;
				cond=false;

				 

			}
		}

	}


	@Override
	public void caretPositionchanged(InputMethodEvent arg0) {
		// TODO Auto-generated method stub

	}}

Was This Post Helpful? 0
  • +
  • -

#12 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • Posts: 2,539
  • Joined: 29-July 11

Re: Java Textfield ONLY NUMBERS

Posted 14 February 2013 - 11:26 PM

Creating a text field that will only let you type numbers in it is absolutely terrible. Your users are going to think your app is broken when nothing happens as start typing letters into the field. You use an InputVerifier for this.

public class Main extends JFrame {
	private JTextField textField1 = new JTextField();
	private JTextField textField2 = new JTextField();
	
	public Main() {
		setSize(200,200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		add(textField1, BorderLayout.NORTH);
		add(textField2, BorderLayout.SOUTH);
		textField1.setInputVerifier(fieldVerifier);
	}

	InputVerifier fieldVerifier = new InputVerifier() {
		@Override
		public boolean verify(JComponent input) {
			JTextField temp = (JTextField)input;
			try {
				int number = Integer.parseInt(temp.getText());
				return true;
			}
			catch(NumberFormatException e) {
				JOptionPane.showMessageDialog(null, "You MUST input only numbers!");
			}
			return false;
		}
	};
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Main().setVisible(true);
			}
		});
	}
}



When focus is switched to another component, the inputverifier will do its work.
Was This Post Helpful? 0
  • +
  • -

#13 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2689
  • View blog
  • Posts: 11,349
  • Joined: 20-September 08

Re: Java Textfield ONLY NUMBERS

Posted 15 February 2013 - 05:42 AM

Yes, i think using an InputVerifier would be a better idea
Was This Post Helpful? 0
  • +
  • -

#14 Buttertoast  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 60
  • Joined: 10-January 13

Re: Java Textfield ONLY NUMBERS

Posted 15 February 2013 - 05:56 AM

It already works, but thanks
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java Textfield ONLY NUMBERS

Posted 15 February 2013 - 07:53 PM

View Postburakaltr, on 14 February 2013 - 11:34 PM, said:

if(!Character.isDigit(i.charAt(y))){

arg0.consume();

}

Cute idea... never though of it
but still prefer my way of doing it, seems less like a hack
But your choice
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2