Java jtextfield only numbers

Allow only numbers in JTextfield [duplicate]

I’m trying to implement requirements like: Accept only numbers in JTextield, when a non-digit key pressed, it will not be accepted. I tried many stuff, even tried to call the backspace event to remove the last character if it’s a non-digit. However, not able to remove the value typed in the textfield. I tried to understand DOCUMENT FILTER but finding it difficult to implement. I will be glad if anyone helps me to resolve the issue.

4 Answers 4

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.

Just curious, what’s the difference between overriding the replace and insertString ? I’m not too familiar with the DocumnetFilter , but just by the name of the method, would insertString be better for this situation? Enlighten me 🙂

«It also overrides the replace method, which is most likely to be called when the user pastes in new text». That’s from the tutorial you linked to. It sound like replace is more for pasted text. Am I wrong?

Читайте также:  Android java с чего начать

Also from text, «insertString method, which is called each time that text is inserted into the document.».

@peeskillet insertString(. ) invokes only when you directly insert text to document like next field.getDocument().insertString(. ); . So you need to override replace() method.

Still can’t upvote because of those terrible variable names. arg0, arg1. mean absolutely nothing to anyone looking at the code.

You can use a MaskFormatter and pass it as the Format argument to the JFormattedTextField constructor.

«The MaskFormatter class implements a formatter that specifies exactly which characters are valid in each position of the field’s text» — MaskFormatter tutorial

This example will only allow user to enter digits. I set it to allow only 6 digits, but you can change that number with more or fewer # ‘s.

import java.awt.BorderLayout; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.text.MaskFormatter; public class MaskFormatterTest extends JPanel < private JFormattedTextField formatText; public MaskFormatterTest() < formatText = new JFormattedTextField(createFormatter("######")); formatText.setColumns(20); setLayout(new BorderLayout()); add(new JLabel("Enter only numbers"), BorderLayout.NORTH); add(formatText, BorderLayout.CENTER); >private MaskFormatter createFormatter(String s) < MaskFormatter formatter = null; try < formatter = new MaskFormatter(s); >catch (java.text.ParseException exc) < System.err.println("formatter is bad: " + exc.getMessage()); System.exit(-1); >return formatter; > public static void main(String[] args) < javax.swing.SwingUtilities.invokeLater(new Runnable() < public void run() < JFrame frame = new JFrame("MaskFormatter example"); frame.add(new MaskFormatterTest()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); >>); > > 

Источник

how to validate a jtextfield to accept only integer numbers [duplicate]

i need to validate a JTextField by allowing the user to input only integer values in it if user enters any char other than numbers a JOptionPane.show messagebox should appear showing that the value entered are incorrect and only integer numbers are allowed. I have coded it for a digit values but i also need to discard the alphabets

public void keyPressed(KeyEvent EVT) < String value = text.getText(); int l = value.length(); if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() else < text.setEditable(false); label.setText("* Enter only numeric digits(0-9)"); >> 

3 Answers 3

Instead of using a JFormattedTextField, you may write a custom JTextField with a document that allows only integers. I like formatted fields only for more complex masks. Take a look.

import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; /** * A JTextField that accepts only integers. * * @author David Buzatto */ public class IntegerField extends JTextField < public IntegerField() < super(); >public IntegerField( int cols ) < super( cols ); >@Override protected Document createDefaultModel() < return new UpperCaseDocument(); >static class UpperCaseDocument extends PlainDocument < @Override public void insertString( int offs, String str, AttributeSet a ) throws BadLocationException < if ( str == null ) < return; >char[] chars = str.toCharArray(); boolean ok = true; for ( int i = 0; i < chars.length; i++ ) < try < Integer.parseInt( String.valueOf( chars[i] ) ); >catch ( NumberFormatException exc ) < ok = false; break; >> if ( ok ) super.insertString( offs, new String( chars ), a ); > > > 

If you are using NetBeans to build your GUI, you just need to put regular JTextFields in your GUI and in the creation code, you will specify the constructor of IntegerField.

Источник

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); 

@Bakhtiyor — The AttributeSet is the collection of attributes (color, font, . ) of the given text. Why not write which error message? I suppose you have to import javax.print.attribute.AttributeSet; .

Hi @CarlosHeuberger. If I want the user to enter only bytes in the JTrextField, then what should I do? For example, I am right now using simply the following: — t3 = new JTextField(«256»); t3.setBounds(100,150,150,20); «256» is just for showing the user the default value in the UI. Thanks & Regards.

sorry @VibhavChaddha not sure what you understand as «only byte», but you can probably use the same concept as above: add a DocumentFilter which rejects (ignores) all changes leading to an invalid value.

@CarlosHeuberger Okay. Thanks. I’ll try that. But to be more specific, I want that the user should not be able to add a value that is more than 256.

Use a JFormattedTextField .

Use a Document implementation whose insertString method filters out the non-digit characters.

Use this class, and call it where you need to validation pass your jtexField name as parameter.

 exm:- setNumericOnly(txtMSISDN); here txtMSISDN is my jtextField. public static void setNumericOnly(JTextField jTextField) < jTextField.addKeyListener(new KeyAdapter() < public void keyTyped(KeyEvent e) < char c = e.getKeyChar(); if ((!Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) < e.consume(); >> >); > 
import javax.swing.text.*; import java.awt.*; public class IntegerDocumentFilter extends DocumentFilter < private AbstractDocument abstractDocument; private IntegerDocumentFilter(AbstractDocument abstractDocument) < this.abstractDocument = abstractDocument; >@Override public void replace(FilterBypass filterBypass, int offset, int length, String input, AttributeSet attributeSet) throws BadLocationException < int inputLength = input.length(); String text = abstractDocument.getText(0, abstractDocument.getLength()); int newLength = text.length() + inputLength; if (isNumeric(input) && newLength else < Toolkit.getDefaultToolkit().beep(); >> private boolean isNumeric(String input) < String regularExpression = "1+"; return input.matches(regularExpression); >public static void addTo(JTextComponent textComponent) < AbstractDocument abstractDocument = (AbstractDocument) textComponent.getDocument(); IntegerDocumentFilter integerDocumentFilter = new IntegerDocumentFilter(abstractDocument); abstractDocument.setDocumentFilter(integerDocumentFilter); >> 
IntegerDocumentFilter.addTo(myTextField); 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Allow textfield to input only number [Java]

I know this has been asked and answered many times but I still can’t get the answer that I really need. Hopefully this time, somebody can help me and I thank you in advance. 🙂 This is what I want in my program, I want user to limit to input only numbers. Whenever they input letters and others there will be a prompt message. I can do that, there is a prompt message for letters and other char but the inputted value still remain, I want it to be cleared. Please see my code.

private void txtQty1KeyTyped(java.awt.event.KeyEvent evt) < txtQty1.addKeyListener(new KeyAdapter() <>); char char_input = evt.getKeyChar(); if (((char_input < '0') || (char_input >'9')) && (char_input != '\b')) < JOptionPane.showMessageDialog(this, "Number only!","Invalid Input",JOptionPane.ERROR_MESSAGE); txtQty1.setText(" "); >> 

Though I clear my textfield, the character that I input still appears. Any help would be much appreciated. Thank you! 🙂

Use a DocumentFilter as demonstrated in: stackoverflow.com/questions/32566597/…. The OP updated the question with a working filter.

2 Answers 2

You need to create a subclass of DocumentFilter class and use a regular expression to match each inserted string/character if they are digits or not and perform actions accordingly.

Below is a fully working sample code of this working. Thanks to @camickr for pointing out using DocumentFilter is more up-to-date than the old way of extending JTextField to achieve the same result.

import java.awt.BorderLayout; import java.util.regex.Pattern; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; public class TestDocumentFilter < public static void main(String. args) < new TestDocumentFilter(); >public TestDocumentFilter() < JTextField textField = new JTextField(10); ((AbstractDocument) textField.getDocument()).setDocumentFilter(new CustomDocumentFilter()); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout(5, 5)); frame.getContentPane().add(textField, BorderLayout.NORTH); frame.setSize(400, 200); frame.setVisible(true); >private class CustomDocumentFilter extends DocumentFilter < private Pattern regexCheck = Pattern.compile("1+"); @Override public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException < if (str == null) < return; >if (regexCheck.matcher(str).matches()) < super.insertString(fb, offs, str, a); >> @Override public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attrs) throws BadLocationException < if (str == null) < return; >if (regexCheck.matcher(str).matches()) < fb.replace(offset, length, str, attrs); >> > > 

Источник

Only numbers and one decimal point allow on jtextfield in java [duplicate]

Please tell me how to do this step by step.

  1. use JFormattedTextField with NumberFormatter
    • restrict number of decimal places
    • set various RoundingModes
    • restrict range, set minimal and/or maximal value
  2. another of ways is to use JSpinner with SPinnerNUmberModel, but required to use DocumentFilter
import java.awt.*; import java.awt.font.TextAttribute; import java.math.*; import java.text.*; import java.util.Map; import javax.swing.*; import javax.swing.JFormattedTextField.*; import javax.swing.event.*; import javax.swing.text.InternationalFormatter; public class DocumentListenerAdapter < public DocumentListenerAdapter() < JFrame frame = new JFrame("AbstractTextField Test"); final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01)); textField1.setFormatterFactory(new AbstractFormatterFactory() < @Override public AbstractFormatter getFormatter(JFormattedTextField tf) < NumberFormat format = DecimalFormat.getInstance(); format.setMinimumFractionDigits(2); format.setMaximumFractionDigits(2); format.setRoundingMode(RoundingMode.HALF_UP); InternationalFormatter formatter = new InternationalFormatter(format); formatter.setAllowsInvalid(false); //formatter.setMinimum(0.0); //formatter.setMaximum(1000.00); return formatter; >>); final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes(); attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON); final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01)); textField2.setFormatterFactory(new AbstractFormatterFactory() < @Override public AbstractFormatter getFormatter(JFormattedTextField tf) < NumberFormat format = DecimalFormat.getInstance(); format.setMinimumFractionDigits(2); format.setMaximumFractionDigits(2); format.setRoundingMode(RoundingMode.HALF_UP); InternationalFormatter formatter = new InternationalFormatter(format); formatter.setAllowsInvalid(false); //formatter.setMinimum(0.0); //formatter.setMaximum(1000.00); return formatter; >>); textField2.getDocument().addDocumentListener(new DocumentListener() < @Override public void changedUpdate(DocumentEvent documentEvent) < printIt(documentEvent); >@Override public void insertUpdate(DocumentEvent documentEvent) < printIt(documentEvent); >@Override public void removeUpdate(DocumentEvent documentEvent) < printIt(documentEvent); >private void printIt(DocumentEvent documentEvent) < DocumentEvent.EventType type = documentEvent.getType(); double t1a1 = (((Number) textField2.getValue()).doubleValue()); if (t1a1 >1000) < Runnable doRun = new Runnable() < @Override public void run() < textField2.setFont(new Font(attributes)); textField2.setForeground(Color.red); >>; SwingUtilities.invokeLater(doRun); > else < Runnable doRun = new Runnable() < @Override public void run() < textField2.setFont(new Font("Serif", Font.BOLD, 16)); textField2.setForeground(Color.black); >>; SwingUtilities.invokeLater(doRun); > > >); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(textField1, BorderLayout.NORTH); frame.add(textField2, BorderLayout.SOUTH); frame.setVisible(true); frame.pack(); > public static void main(String args[]) < java.awt.EventQueue.invokeLater(new Runnable() < @Override public void run() < DocumentListenerAdapter main = new DocumentListenerAdapter(); >>); > > 

Источник

Оцените статью