0

How to set a limit to the input for user, I mean that the user can input only like 2 or 4 integers and no more.

Code:

 JLabel dateD = new JLabel("| Date  Day:");
 dateD.setBounds(170,270, 120, 25);

 dateDD = new JTextField();
 dateDD.setBounds(235,270, 20, 25);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Denis Nurasy
  • 41
  • 1
  • 8
  • 1
    Don't use `setBounds()` to set the size/locaton of components. Swing was designed to be used with [Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). – camickr Mar 26 '13 at 18:20
  • I KNOW , you are not the first person who told me to use LayoutManager I need to use this method.... and question is how to make fixed INT with this method that I have used.......((( – Denis Nurasy Mar 26 '13 at 18:23
  • So why do you continue to ask for help if you ignore the advice given? – camickr Mar 26 '13 at 19:57
  • I ask how to make fixed input with this way if it not possible using this method just say it THIS IS NOT POSSIBLE that's all what I ask... – Denis Nurasy Mar 26 '13 at 20:39
  • I have no idea what you are talking about. You have been told it is posssible and you have been give the code to use. All you have to do is download the code from the tutorial and add it to your program. – camickr Mar 26 '13 at 21:34

2 Answers2

1

Using DocumentFilter should sort you out, create the filter as follows :-

class MaximumCharacters extends DocumentFilter {

        private int maxLength;

        public MaximumCharacters() {
            maxLength = 10; // The number of characters allowed
        }

        @Override
        public void insertString(FilterBypass fb, int offset, String string,
                AttributeSet attr) throws BadLocationException {
            if (maxLength > 0
                    && fb.getDocument().getLength() + string.length() <= maxLength) {
                super.insertString(fb, offset, string, attr);
            }
        }

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

            if ((fb.getDocument().getLength() + text.length() - length) <= maxLength)
                super.replace(fb, offset, length, text, attrs);
        }
    }

Then you set the DocumentFilter to your JTextField component as follows :-

((AbstractDocument) dateDD.getDocument()).setDocumentFilter(new MaximumCharacters());
tmwanik
  • 1,643
  • 14
  • 20
  • +1 for the DocumentFilter. See the Swing tutorial [Implementing a Document Filter](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) for more information. – camickr Mar 26 '13 at 18:21
  • Can you explain a bit more how to use DocumentFilter? – Denis Nurasy Mar 26 '13 at 18:22
  • -1, I originally upvoted for the suggestion to use a DocumentFilter, which is the correct approach to solve the problem. Instead you posted code extending a Document, which is NOT the preferred approach. Its is also confusing since the code has nothing to do with the suggestion to use a DocumentFilter. – camickr Mar 26 '13 at 20:01
  • @DenisNurasy, then you obvsiously didn't read the tutorial link I provided, since it includes working code and explanations about the code. – camickr Mar 26 '13 at 20:02
  • I have read, I just can't get this.... can't visualise how this method works this is the problem, and that's why I asked this question up here.... – Denis Nurasy Mar 26 '13 at 20:46
  • I don't know how you expect us to help. The tutorial provides working code for the DocumentFilter. It show the 4-5 lines of code needed to add the filter to the text field. It also explains the concept of a DocumentFilter. You haven't stated what it is that you don't understand. Did you even download the code and try it? If so then why didn't you post an SSCCE showing what you did? – camickr Mar 26 '13 at 21:33
  • @camickr thank you for the comments, i have revised my answer – tmwanik Mar 26 '13 at 22:54
0

For the above answer below is a Utility method I have created to deal with above situations -

    /**
     * Method installNumericMaximumCharacters.
     * 
     * @param document
     *            AbstractDocument
     * @param numberofChars
     *            int
     */
    public static void installNumericMaximumCharacters(
            AbstractDocument document, final int numberofChars) {
        document.setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {
                try {
                    if (string.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, string, attr);
                        return;
                    }
                    Double.parseDouble(string);
                    if (fb.getDocument().getLength() + string.length() <= numberofChars) {
                        super.insertString(fb, offset, string, attr);
                    } else {
                        Toolkit.getDefaultToolkit().beep();
                    }
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                    String text, AttributeSet attrs)
                    throws BadLocationException {
                try {
                    if (text.equals(".")
                            && !fb.getDocument()
                                    .getText(0, fb.getDocument().getLength())
                                    .contains(".")) {
                        super.insertString(fb, offset, text, attrs);
                        return;
                    }
                    Double.parseDouble(text);
                    int l = fb.getDocument().getLength() - length
                            + text.length();
                    if (length > 0) {
                        fb.getDocument().remove(offset, length);
                    }
                    if (l <= numberofChars) {
                        super.insertString(fb, offset, text, attrs);

                    } else {
                        Toolkit.getDefaultToolkit().beep();
                    }
                } catch (Exception e) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
    }

The method is bit self explanatory. When ever a change occurs on the Document it will evoke the DocumentFilter. Beware that you cannot setText() the same Document. You will have to use the FilterBypass object for it.

Chan
  • 2,601
  • 6
  • 28
  • 45