Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8372103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T14:20:10+00:00 2026-06-09T14:20:10+00:00

Below is the KeyAdapter I tried to get working to only accept values less

  • 0

Below is the KeyAdapter I tried to get working to only accept values less than 65535. It seems as though it gets it one keystroke behind where it actually should. For example, If I type “55”, the System.out.println will yield “5”, doing “3298” will yield “329”, etc.

// Allows for unsigned short values only
KeyAdapter unsignedShortAdapter = new KeyAdapter() {

    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        int tempInt = 0;
        JTextField temp = null;

        if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
            getToolkit().beep();
            e.consume();
        }
        try {
            temp = (JTextField) e.getSource();
            System.out.println(temp.getText());
            tempInt = (Integer.parseInt(temp.getText().toString()));
        } catch (NumberFormatException e1) {

        } finally {
            if (tempInt > (Short.MAX_VALUE * 2)) {
                 getToolkit().beep();
                 e.consume();
                temp.setText(temp.getText().substring(0, temp.getText().length() - 1));

                invalidate();
            }

        }
    }

};
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T14:20:12+00:00Added an answer on June 9, 2026 at 2:20 pm

    So, instead of a KeyListener, which you’ve found, is unreliable and will cause lots of nasty side effects (and possible Document Mutation exceptions :P), we should use a DocumentFilter, cause that’s what it’s designed for

    public class ShortFilter extends DocumentFilter {
    
        protected boolean valid(String text) {
    
    
            boolean valid = true;
            for (char check : text.toCharArray()) {
    
                if (!Character.isDigit(check)) {
    
                    valid = false;
                    break;
    
                }
    
            }
    
            if (valid) {
    
                int iValue = Integer.parseInt(text);
    
                valid = iValue <= (Short.MAX_VALUE * 2);
    
            }
    
            return valid;
    
        }
    
        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
    
            StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
            sb.insert(offset, text);
    
            if (valid(sb.toString())) {
    
                super.insertString(fb, offset, text, attr);
    
            }
    
        }
    
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
    
            if (length > 0) {
    
                StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
    
                sb.delete(offset, length);
                sb.insert(offset, text);
    
                if (valid(sb.toString())) {
    
                    super.replace(fb, offset, length, text, attrs);
    
                }
    
            } else {
    
                insertString(fb, offset, text, attrs);
    
            }
    
        }
    }
    

    You will need to apply this to the field’s document

    ((AbstractDocument) field.getDocument()).setDocumentFilter(new ShortFilter());
    

    I’d check out

    • http://www.jroller.com/dpmihai/entry/documentfilter
    • http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DocumentFilter.html

    For some more info

    UPDATE for Decimal inclusion

    Basically, if you want to allow the inclusion of a decimal, you need to allow for the character in the valid method.

    You also need to check the current document’s contents

    StringBuilder sb = new StringBuilder(fb.getDocument().getText(0, fb.getDocument().getLength()));
    
    // Update the StringBuilder as per noraml
    // Check valid as per normal
    
    if (text.contains(".") && sb.contains(".")) {
      // already have decimal place
    } else {
      // Business as usual...
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Below is the plugin code that i have tried to reuse from an old
Below is the code I use in Chrome extension which gets a url from
Below is my simple graph on high charts. Everything appears fine but only problem
Below is my code. Collisions actually register and execute, but only if your ship
below I have a query that will get the most common user agents for
Below is code that sits in an iframe. I'm able to get the variable
Below command returns with time stamp, how do I get rid of the time:
Below is my $.ajax call, how do I put a selects (multiple) selected values
Below is my view page. without <form> tag when I insert the values, its
Below is an image of a ListView row that is too short. I've tried

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.