Link to home
Start Free TrialLog in
Avatar of tbboyett
tbboyettFlag for United States of America

asked on

Textfield keylistener problem

I have the below code

textfield.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
            filterStr = filterKeyTyped(evt, textfield.getText().trim());    
            System.out.println(filterStr)
});

private String filterKeyTyped(KeyEvent e, String string) {
        if(e.getKeyChar() == 8 ){ // backspace character was hit
            int length = string.length();
            if(length > 1) {
                string = string.substring(0, length - 1).toUpperCase();
            }
            else {
                string = "";
            }
        }
        else {
            string += e.getKeyChar();
        }

        if (!isNumber(string)) {
            string = "";
        }
       
        return (string);
    }

    public boolean isNumber(String text) {
        try {
            int test = Integer.parseInt(text.trim());
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

Works fine except for one problem, if the user selects all of the text in the textfield and hits delete, it only removes one character from the string.
How can i detect if they highlight all the text and delete it so i can set the string back to nothing?
Avatar of BogoJoker
BogoJoker

Hi tbboyett,

public String getSelectedText();

check if that is not null or its length is greater then 0

Joe P
Avatar of CEHJ
You'd be better to use a DocumentListener or a custom Document, or you'll only be able to operate 'key-wise'
Here are the java docs:
http://java.sun.com/j2se/1.5.0/docs/api/

Browse to: JTextField
getSelectedText() is one of its public methods.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tbboyett

ASKER

> getSelectedText()

I've tried the getselectedtext but for some reason returns null when they select all the text and click backspace or delete

> You'd be better to use a DocumentListener or a custom Document, or you'll only be able to operate 'key-wise'

Can explain briefly about the DocumentListener or do you have short example I can view?
> http://javaalmanac.com/egs/javax.swing.text/ChangeEvt.html

looks like what I need, i'll give it a shot
Works perfect, just one last quick question.  Is there a quick and easy way to limit a textfield to a certain amount of characters or will i just need to check each time to see how many are entered?
You could use a custom Document to do that.
:-)