This site requires JavaScript, please enable it in your browser!
Greenfoot back
Commentator
Commentator wrote ...

2021/1/22

Text/char input

Commentator Commentator

2021/1/22

#
Is there any way to get text/char input that takes shift ctrl etc into account when returning the character? and also returns space as " " and not as the word?
Commentator Commentator

2021/1/22

#
currently i am using
    public boolean checkKey(String key) {
        if (key == null) if (Greenfoot.getKey() != null) return true; else return false;
        if (Greenfoot.isKeyDown(key)) {
            if (! pressed_keys.contains(key)) {
                pressed_keys.add(key);
                return true;
            }
        }
        else {
            pressed_keys.remove(key);
        }
        return false;
    }

    public String getCurrentKey() {
        String key = Greenfoot.getKey();
        if (!checkKey(key)) return "";
        if (key.equals("shift") ||
                key.equals("control") ||
                key.equals("enter") ||
                key.equals("tab") ||
                key.equals("backspace") ||
                key.equals("up") ||
                key.equals("down") ||
                key.equals("left") ||
                key.equals("right") ||
                key.equals("escape")
            ) return "";
        for (int i = 0; i < 12; i ++) {
            if (key.equals("F"+i)) return "";
        }
        if (key.equals("space")) return " ";
        if (Greenfoot.isKeyDown("shift")) {
            return key.toUpperCase();
        }
        else return key;
    }
(pressed_keys being an ArrayList) but it shouldn't be necessary for the user to always have to include such code in each project and this still doesn't work for shifting on numbers (for special characters)
Super_Hippo Super_Hippo

2021/1/22

#
For typing text, you can use the “Greenfoot.getKey” function. To not type words like “space” instead of doing an actual space, you need to compare the output before you put it behind the String.
String someString = "";

//...

String key = Greenfoot.getKey();
if (key != null)
{
    if ("space".equals(key)) someString += " ";
    //else if ("...what ever you also want to do something special...".equals(key)) ...
    else if (key.length() > 1) {} //ignore everything else with more than a single character
    else someString += key;
}
danpost danpost

2021/1/22

#
Might want to also restrict the key returned to being character values of at least 32 (to printable characters). Line 10 in Hippo's code could be:
else if (key.length() > 1 || key.charAt(0) < 32) {}
You need to login to post a reply.