Results 1 to 7 of 7
  1. #1
    Zepher is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default Overriding KeyListener but still allowing input?

    I have the following code:

    Java Code:
    betInput.addKeyListener(new KeyListener()
            {
                public void keyTyped(KeyEvent e){
                    //ACTIONS GO HERE
                    try{
                        currentBet = Integer.parseInt(betInput.getText());
                    }
                    catch(NumberFormatException ex){
                        betInput.setText(currentBet.toString());
                    }
                }
    
                public void keyReleased(KeyEvent e)
                {}
           
                public void keyPressed(KeyEvent e)
                {}
                
            });
    and I am trying to ensure that a value is an integer and to only add it to the JTextField if it is. I just don't know what I need to add the typed key into the field.

    Any help would be appreciated.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Don't use a KeyListener for this. What happens for instance if the user pastes text into the field that is non-numeric? Instead use a DocumentFilter. The Swing tutorials will tell you how to use these, and you can search this forum for some decent examples too.

  3. #3
    Zepher is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Fubarable, thank you for the response. I'm sorry that it took me so long to get back to this, I've been busy with other, real projects.

    I have looked at a DocumentFilter and built one for my uses. I just have one remaining question - what type of listener should I use to update my text field? I tried ActionListener but that doesn't seem correct and, from before, you told me I shouldn't be using a KeyListener.

    Thanks.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by Zepher View Post
    Fubarable, thank you for the response. I'm sorry that it took me so long to get back to this, I've been busy with other, real projects.

    I have looked at a DocumentFilter and built one for my uses. I just have one remaining question - what type of listener should I use to update my text field? I tried ActionListener but that doesn't seem correct and, from before, you told me I shouldn't be using a KeyListener.

    Thanks.
    What do you mean "to update my field"? Can you be more specific and provide the important details?

  5. #5
    Zepher is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    I need some way to use the documentFilter whenever a user types or pastes text in the text field. The only way I know to modify a swing element is by using some type of listener.

    This is what I tried:

    Java Code:
            betInput.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    betInput.setDocument(new IntFilter(IntFilter.DECIMALS));
                }
            });
    and I am uncertain of the inner workings of the document filter but here is what I have on that:

    Java Code:
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
    
    class IntFilter extends PlainDocument {
      public static final String DECIMALS = "0123456789";
    
      protected String acceptedChars = null;
    
      protected boolean negativeAccepted = false;
    
      public IntFilter() {
        this(DECIMALS);
      }
    
      public IntFilter(String acceptedchars) {
        acceptedChars = acceptedchars;
      }
    
      public void setNegativeAccepted(boolean negativeaccepted) {
        if (acceptedChars.equals(DECIMALS)) {
          negativeAccepted = negativeaccepted;
        }
      }
    
      public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null)
          return;
    
        for (int i = 0; i < str.length(); i++) {
          if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
            return;
        }
    
        if (acceptedChars.equals(DECIMALS) || (acceptedChars.equals(DECIMALS + "-") && negativeAccepted)) {
          if (str.indexOf(".") != -1) {
            if (getText(0, getLength()).indexOf(".") != -1) {
              return;
            }
          }
        }
    
        if (negativeAccepted && str.indexOf("-") != -1) {
          if (str.indexOf("-") != 0 || offset != 0) {
            return;
          }
        }
    
        super.insertString(offset, str, attr);
      }
    }
    but the actionListener is not called whenever I type in the text field so I haven't even been able to test my code.

    I hope this makes things clearer? By the way, thanks for always being around so often!

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I don't see where you've even created a DocumentFilter instance much less where you've added one to the text component's document. Did you read the tutorial on how to create and use these? If so, I think you would benefit from re-reading it.

    Edit: here is the relevant portion: DocumentFilter

    Edit 2: here is a DocumentFilter that I wote in answering a question posted in this forum: limit number of cols jtextarea again

    Luck
    Last edited by Fubarable; 02-14-2011 at 06:28 AM.

  7. #7
    Zepher is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    I see whats going on, you don't instantiate the documentFilter each time, its only done once after you create the text field. In my first block of code, you will see that I did create a DocumentFilter and, upon reading your comments, I realized what I did wrong. Everything seems to be working great now, thanks again.

Similar Threads

  1. Allowing only hex values in a textfield
    By elsanthosh in forum AWT / Swing
    Replies: 3
    Last Post: 07-20-2010, 09:31 AM
  2. Overriding
    By renuka_renukut in forum Advanced Java
    Replies: 3
    Last Post: 05-21-2010, 08:45 AM
  3. Replies: 6
    Last Post: 04-28-2010, 12:49 AM
  4. regex problem - allowing optional space
    By Norm in forum Advanced Java
    Replies: 26
    Last Post: 10-06-2008, 04:38 PM
  5. Allowing only numeric values in a TextField
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-01-2008, 10:08 PM

Posting Permissions

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