Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    hooks keyboard browser (java)

    I have an input field that i want to enter only numbers. There is a way to block all other keys except number keys and numpad key? Because i don't know java, can anyone know a good example about it, or something to search in google? I found some links, but i don't understand a lot. Thanks in advance.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    You can listen for the events and respond accordingly, but its probably easier to just set the DocumentFilter. Here's a quick example using an anonymous class:
    PHP Code:
        public static void main(String... argv)
        {
            
    JFrame f = new JFrame();
            
    JTextField field = new JTextField();

            if (
    field.getDocument() instanceof AbstractDocument)
            {
                ((
    AbstractDocumentfield.getDocument()).setDocumentFilter(new DocumentFilter()
                {
                    public 
    void replace(FilterBypass fbint offsint lengthString strAttributeSet athrows BadLocationException
                    
    {
                        try
                        {
                            
    Integer.parseInt(str);
                            
    super.replace(fboffslengthstra);
                        }
                        catch (
    NumberFormatException ex)
                        {
                            
    // Don't care, just abandon it.
                        
    }
                    }
                });
            }
            
    f.add(field);
            
    f.pack();
            
    f.setVisible(true);
            
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        } 


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •