36

Does anyone knows how to detect printable characters in java?

After a while ( trial/error ) I get to this method:

    public boolean isPrintableChar( char c ) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
        return (!Character.isISOControl(c)) &&
                c != KeyEvent.CHAR_UNDEFINED &&
                block != null &&
                block != Character.UnicodeBlock.SPECIALS;
    }

I'm getting the input via KeyListener and come Ctr-'key' printed an square. With this function seems fairly enough.

Am I missing some char here?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 2
    I've never understood why Java does not have a `Character.isPrintable()` method. Another technique is to compare `Character.getType(ch)` with all of the printable Unicode character classes, which still seems like a lot of effort to go to. – David R Tribble May 04 '15 at 15:16
  • You should consider this, this answer did this for me: http://stackoverflow.com/a/41100873/5285687 – YellowJ Feb 28 '17 at 08:18

2 Answers2

45

It seems this was the "Font" independent way.

public boolean isPrintableChar( char c ) {
    Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
    return (!Character.isISOControl(c)) &&
            c != KeyEvent.CHAR_UNDEFINED &&
            block != null &&
            block != Character.UnicodeBlock.SPECIALS;
}
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
15

I'm not perfectly sure whether I understand your problem. But if you want detect if character can be drawn to Graphics object, and if not print some placeholder char you might find usefull:

Font.canDisplay(int)

It will check whether font can display specific codepoint (it is more that check whether font is displayable at all -- since there are chars that are displayable - like ą - but some fonts cant display them.

jb.
  • 23,300
  • 18
  • 98
  • 136
  • This worked also. Thank you. I'm printing on a jlabel all the character written in the key board. With out this validation ^c , "RETURN" "ESC" F1..F12 characters are displayed as strange little squares. Both (my function and your method ) filter them properly. I guess I should add some test case. – OscarRyz Oct 24 '08 at 17:29
  • Ok, It worked with the characters in my keyboard, but after iterate from 0 to Character.MAX_VALUE there are a number of chars that cannot be displayed by Font.canDisplay() around char 384. That depends on user font. Both will work. Thank you – OscarRyz Oct 24 '08 at 18:35