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);
}
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
JTextField accept only numbers and one dot
Don't use a KeyListener. That is old code when using AWT.
Swing has newer and better API's.
The easiest way is to use a JFormattedTextField
. Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and working examples.
The other option is so use a DocumentFilter
. Read the section from the Swing tutorial on Implementing a DocumentFilter.
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);
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("");
}
synchronize jtextfield value into only integer value using document listener
You're getting NumberFormatException
because nothing can't be converted to a number, when you clear the text from field
so you need to check if the field is empty.
if (!text.isEmpty()) {
int p = Integer.parseInt(text);
int i = (p * 5);
String s = String.valueOf(i);
field1.setText(s);
} else {
field1.setText(null);
}
Also as I noted in the comments, with links, just use a DocumentFilter
allow only numbers.
Here is a refactor of your code. It works without the NumberFormatException
. I added the DocumentFilter
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
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 TestLabelMirror {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(20);
private JTextField field1 = new JTextField(20);
private JFrame frame;
public TestLabelMirror() {
field.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
String text = field.getText();
String text1 = field1.getText();
if (!text.isEmpty()) {
int p = Integer.parseInt(text);
int i = (p * 5);
String s = String.valueOf(i);
field1.setText(s);
} else {
field1.setText(null);
}
}
});
}
});
((AbstractDocument) field.getDocument()).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
}
});
mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
mainPanel.add(field);
mainPanel.add(field1);
}
public JComponent getComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("TextLabelMirror");
frame.getContentPane().add(new TestLabelMirror().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
}
Setting enterable characters in JTextField
By setting a custom Document in your JTextField that would insert only numeric values in it.
As shown in Oracle documententation about JTextField:
public class UpperCaseField extends JTextField {
public UpperCaseField(int cols) {
super(cols);
}
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
char[] upper = str.toCharArray();
for (int i = 0; i < upper.length; i++) {
upper[i] = Character.toUpperCase(upper[i]);
}
super.insertString(offs, new String(upper), a);
}
}
}
Read more: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html
Related Topics
Break or Return from Java 8 Stream Foreach
How to Configure Maven for Offline Development
When and Why JPA Entities Should Implement the Serializable Interface
Integer.Tostring(Int I) VS String.Valueof(Int I)
Displaying Currency in Indian Numbering Format
Password Protected Zip File in Java
Changing Mercury Color in Thermometer in Jfreechart
How Does the Jvm Decided to Jit-Compile a Method (Categorize a Method as "Hot")
How to Define Custom Exception Class in Java, the Easiest Way
Format Double Value in Scientific Notation
Map Enum in JPA with Fixed Values
Green Threads VS Non Green Threads
Move/Copy File Operations in Java
Expression Language in Jsp Not Working
Parsing a Date's Ordinal Indicator ( St, Nd, Rd, Th ) in a Date-Time String