Restricting a TextField input to hexadecimal values in Java FX

后端 未结 3 1808
Happy的楠姐
Happy的楠姐 2021-01-21 20:37

How can I restrict the input from the user to only hexadecimal values? With decimal notation the range is from 0 to 16383, but I would like to let the user type an hexadecimal n

3条回答
  •  面向向阳花
    2021-01-21 21:36

    An idea may be to parse it into integer format first. You can use:

    int value = Integer.decode("your hex value here");

    if the string is not a proper value, it will throw a number format exception, however the decode function will also work for any valid integer (so something base 10 will work as well in this case).

    An alternative you could try is:

    int value = Integer.parseInt("hex value",16)

    However for this method you will need to get rid of the "0x" header from your String

    Since you are performing a check, surround it with a try catch block and whatever is caught would be an improperly formatted hex.

    Furthermore if you need to check whether the value is between 0 to 16383, just use the value returned by the methods above.

提交回复
热议问题