{"id":788,"date":"2022-08-24T14:05:12","date_gmt":"2022-08-24T08:35:12","guid":{"rendered":"https:\/\/openapex.org\/spaces\/software\/?p=788"},"modified":"2022-08-24T14:05:12","modified_gmt":"2022-08-24T08:35:12","slug":"how-to-enforce-jtextfield-to-allow-only-numeric-input-data-of-limited-length","status":"publish","type":"post","link":"https:\/\/mutesoft.com\/spaces\/software\/how-to-enforce-jtextfield-to-allow-only-numeric-input-data-of-limited-length.html","title":{"rendered":"How to Enforce JTextField to Allow Only Numeric Input Data of Limited Length?"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"512\" src=\"https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-1024x512.jpg\" alt=\"Java Swing Numeric Text Field\" class=\"wp-image-1191\" srcset=\"https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-1024x512.jpg 1024w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-300x150.jpg 300w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-768x384.jpg 768w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-1536x768.jpg 1536w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-2048x1024.jpg 2048w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-500x250.jpg 500w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-800x400.jpg 800w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-1280x640.jpg 1280w, https:\/\/mutesoft.com\/spaces\/software\/wp-content\/uploads\/sites\/7\/2022\/08\/Numeric-Text-Field-1920x960.jpg 1920w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Java Swing Numeric Text Field<\/figcaption><\/figure>\n\n\n\n<p>The <code>JTextField<\/code> component in <code>javax.swing<\/code> package is a general-purpose text field that accepts any input character. Often applications need to restrict the text field to accept only a certain type of inputs. One such use case is &#8211; the text field only allows numbers without decimal points (integers) and also it must restrict the length of characters.<\/p>\n\n\n\n<p>We are going to use <code>javax.swing.text.DocumenntFilter<\/code> for this purpose. The document filter attached to the text field would perform validations while inserting ore replacing text in the text field. <\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_79_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/mutesoft.com\/spaces\/software\/how-to-enforce-jtextfield-to-allow-only-numeric-input-data-of-limited-length.html\/#1_Filter_to_Allow_Only_Numeric_Input_of_Limited_Length\" >1. Filter to Allow Only Numeric Input of Limited Length<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/mutesoft.com\/spaces\/software\/how-to-enforce-jtextfield-to-allow-only-numeric-input-data-of-limited-length.html\/#2_Runner_Code\" >2. Runner Code<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/mutesoft.com\/spaces\/software\/how-to-enforce-jtextfield-to-allow-only-numeric-input-data-of-limited-length.html\/#3_Download\" >3. Download<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1_Filter_to_Allow_Only_Numeric_Input_of_Limited_Length\"><\/span>1. Filter to Allow Only Numeric Input of Limited Length<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>NumericAndLengthFilter<\/code> takes length argument in the constructor to impose input length restriction on <code>JTextField<\/code>. Both <code>insertString()<\/code> and <code>replace()<\/code> methods are overridden so that not only key input, but pasted data from the clipboard also can be validated. Both the methods calculate the effective length considering the current data on the field and the new incoming data. If the length is within the permissible range, the input data is then validated for the numeric check using a simple number test method.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/**\n * A document filter for numeric and length check.\n *\/\nprivate class NumericAndLengthFilter extends DocumentFilter {\n\n    \/**\n     * Number of characters allowed.\n     *\/\n    private int length = 0;\n\n    \/**\n     * Restricts the number of charcacters can be entered by given length.\n     * \n     * @param length Number of characters allowed.\n     *\/\n    public NumericAndLengthFilter(int length) {\n        this.length = length;\n    }\n\n    @Override\n    public void insertString(FilterBypass fb, int offset, String string,\n            AttributeSet attr) throws BadLocationException {\n        if (isNumeric(string)) {\n            if (this.length > 0 &amp;&amp; fb.getDocument().getLength() + string.length() > this.length) {\n                return;\n            }\n            super.insertString(fb, offset, string, attr);\n        }\n    }\n\n    @Override\n    public void replace(FilterBypass fb, int offset, int length, String text,\n            AttributeSet attrs) throws BadLocationException {\n        if (isNumeric(text)) {\n            if (this.length > 0 &amp;&amp; fb.getDocument().getLength() + text.length() > this.length) {\n                return;\n            }\n            super.insertString(fb, offset, text, attrs);\n        }\n    }\n}<\/pre>\n\n\n\n<p>The below method checks whether the supplied string is a number. This method does not even allow decimal point. However, the implementation of these methods can be enhanced further according to the requirement.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/**\n * This method tests whether given text can be represented as number.\n * This method can be enhanced further for specific needs.\n * \n * @param text Input text.\n * @return {@code true} if given string can be converted to number; otherwise\n *         returns {@code false}.\n *\/\nprivate boolean isNumeric(String text) {\n    if (text == null || text.trim().equals(\"\")) {\n        return false;\n    }\n    for (int iCount = 0; iCount &lt; text.length(); iCount++) {\n        if (!Character.isDigit(text.charAt(iCount))) {\n            return false;\n        }\n    }\n    return true;\n}<\/pre>\n\n\n\n<p>In case typed in or copied data is invalid, insert or replace operation is discarded. So, now we have successfully implemented a numeric text field with the help of a <code>javax.swing.text.DocumentFilter<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2_Runner_Code\"><\/span>2. Runner Code<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In <code>createUI()<\/code> method, as usual, an instance of <code>JTextField<\/code> is created and then added to a <code>JPanel<\/code>. To put restrictions on the <code>JTextField<\/code>, we use <code>javax.swing.text.DocumentFilter<\/code>. <code>DocumentFilter<\/code> provides a mechanism to apply a filter on document associated with swing text components such as <code>JTextField<\/code>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/**\n * NumericTextField allows only numbers in the text field and not even decimal\n * points. Also, it restricts the length of input.\n *\/\npublic class NumericTextField {\n\n    \/**\n     * Creates the UI with the text field that accepts numeric data of specified\n     * length.\n     *\/\n    public void createUI() {\n        final JFrame frame = new JFrame(\"NumericTextField\");\n        frame.setSize(400, 400);\n        JPanel panel = new JPanel();\n        JLabel label = new JLabel(\"Enter some data (only numbers would be allowed):\");\n        final JTextField textField = new JTextField(30);\n        \/\/ Add the document filter to text field for numeric and length check.\n        ((AbstractDocument) textField.getDocument()).setDocumentFilter(new NumericAndLengthFilter(\n                5));\n        panel.add(label);\n        panel.add(textField);\n        frame.getContentPane().add(panel);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        frame.setVisible(true);\n    }\n\n    \/**\n     * Entry point of the application.\n     * \n     * @param args Input arguments.\n     *\/\n    public static void main(String[] args) {\n        final NumericTextField test = new NumericTextField();\n        SwingUtilities.invokeLater(new Runnable() {\n\n            public void run() {\n                test.createUI();\n            }\n        });\n    }\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3_Download\"><\/span>3. Download<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You may download the complete source code from here: <a href=\"\/common\/download.php?f=NumericTextField.java\" target=\"_blank\" rel=\"noreferrer noopener\">NumericTextField.java<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The JTextField component in javax.swing package is a general-purpose text field that accepts any input character. Often applications need to restrict the text field to accept only a certain type of inputs. One such use case is &#8211; the text field only allows numbers without decimal points (integers) and also it must restrict the length of characters.<\/p>\n","protected":false},"author":2,"featured_media":1191,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_seopress_robots_primary_cat":"none","_seopress_titles_title":"","_seopress_titles_desc":"","_seopress_robots_index":"","_vp_format_video_url":"","_vp_image_focal_point":[],"footnotes":""},"categories":[6],"tags":[9,60],"class_list":["post-788","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-programming","tag-java","tag-swing"],"_links":{"self":[{"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/posts\/788","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/comments?post=788"}],"version-history":[{"count":11,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/posts\/788\/revisions"}],"predecessor-version":[{"id":1193,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/posts\/788\/revisions\/1193"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/media\/1191"}],"wp:attachment":[{"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/media?parent=788"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/categories?post=788"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mutesoft.com\/spaces\/software\/wp-json\/wp\/v2\/tags?post=788"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}