How to Implement in Java ( Jtextfield Class ) to Allow Entering Only Digits

How to allow introducing only digits in jTextField?

Here check this code snippet, that's how you allow only digits in JTextField, by using DocumentFilter, as the most effeciive way :

import java.awt.*;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class InputInteger
{
private JTextField tField;
private MyDocumentFilter documentFilter;

private void displayGUI()
{
JFrame frame = new JFrame("Input Integer Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
tField = new JTextField(10);
((AbstractDocument)tField.getDocument()).setDocumentFilter(
new MyDocumentFilter());
contentPane.add(tField);

frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
new InputInteger().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}

class MyDocumentFilter extends DocumentFilter
{
@Override
public void insertString(DocumentFilter.FilterBypass fp
, int offset, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;

for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.insertString(fp, offset, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}

@Override
public void replace(DocumentFilter.FilterBypass fp, int offset
, int length, String string, AttributeSet aset)
throws BadLocationException
{
int len = string.length();
boolean isValidInteger = true;

for (int i = 0; i < len; i++)
{
if (!Character.isDigit(string.charAt(i)))
{
isValidInteger = false;
break;
}
}
if (isValidInteger)
super.replace(fp, offset, length, string, aset);
else
Toolkit.getDefaultToolkit().beep();
}
}

Or one can simply use this approach, as given by @Carlos Heuberger

@Override
public void insertString(FilterBypass fb, int off
, String str, AttributeSet attr)
throws BadLocationException
{
// remove non-digits
fb.insertString(off, str.replaceAll("\\D++", ""), attr);
}
@Override
public void replace(FilterBypass fb, int off
, int len, String str, AttributeSet attr)
throws BadLocationException
{
// remove non-digits
fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}

How to implement in Java ( JTextField class ) to allow entering only digits?

Add a DocumentFilter to the (Plain)Document used in the JTextField to avoid non-digits.

PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException
{
fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException
{
fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
});

JTextField field = new JTextField();
field.setDocument(doc);

Allow only numbers in JTextfield

Use DocumentFilter. Here is simple example with regex:

JTextField field = new JTextField(10);
((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter(){
Pattern regEx = Pattern.compile("\\d*");

@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
Matcher matcher = regEx.matcher(text);
if(!matcher.matches()){
return;
}
super.replace(fb, offset, length, text, attrs);
}
});

field is your JTextField, and this filter allow to enter only digits.

Java Swing JTextField - Only Numbers

You just need to convert your -

JTextField deg;

to

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
DecimalFormat decimalFormat = (DecimalFormat) numberFormat;
decimalFormat.setGroupingUsed(false);
deg = new JFormattedTextField(decimalFormat);
deg.setColumns(15); //whatever size you wish to set

This will return a general-purpose number format for the current default locale.

Thanks

Make JTextField accept only one digit

Try using the DocumentFilter class. This will allow you to check the input before it is actually shown. You can also edit what I have below to check for only integers.

JTextField tf = new JTextField();
AbstractDocument d = (AbstractDocument) tf.getDocument();
d.setDocumentFilter(new DocumentFilter(){
int max = 1;

@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
int documentLength = fb.getDocument().getLength();
if (documentLength - length + text.length() <= max)
super.replace(fb, offset, length, text.toUpperCase(), attrs);
}
});

java - How to set jtextfield can be filled by numbers only and popup a message dialog on jbutton

Use regex

if(!txtphone.getText().matches("\\d+")){
JOptionPane.showMessageDialog(rootPane, "Input must number");
txtphone.setText("");
}

Accept only numbers and a dot in Java TextField

As suggested by Oracle ,Use Formatted Text Fields

Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field.

amountFormat = NumberFormat.getNumberInstance();
...
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);

Restricting JTextField input to Integers

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

For example: using-documentfilter-filterbypass

Also for tutorial help, please look at: Implementing a DocumentFilter.

Edit

For instance:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
public static void main(String[] args) {
JTextField textField = new JTextField(10);

JPanel panel = new JPanel();
panel.add(textField);

PlainDocument doc = (PlainDocument) textField.getDocument();
doc.setDocumentFilter(new MyIntFilter());

JOptionPane.showMessageDialog(null, panel);
}
}

class MyIntFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {

Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);

if (test(sb.toString())) {
super.insertString(fb, offset, string, attr);
} else {
// warn the user and don't allow the insert
}
}

private boolean test(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}

@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {

Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);

if (test(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
} else {
// warn the user and don't allow the insert
}

}

@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);

if (test(sb.toString())) {
super.remove(fb, offset, length);
} else {
// warn the user and don't allow the insert
}

}
}

Why is this important?

  • What if the user uses copy and paste to insert data into the text component? A KeyListener can miss this?
  • You appear to be desiring to check that the data can represent an int. What if they enter numeric data that doesn't fit?
  • What if you want to allow the user to later enter double data? In scientific notation?


Related Topics



Leave a reply



Submit