jTextField validation for numbers and one decimal point?

前端 未结 5 1397
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 02:52

I need to set a jTextField to accept only numbers and one decimal point.Nothing else. Decimal point can\'t be typed more than once and no other characters are allowed. How c

5条回答
  •  遥遥无期
    2020-12-20 03:23

    You appear to be using a KeyListener to manage KeyEvents in theJTextField. This is not a suitable for filtering the document of this JTextComponent. Here you could use a JFormattedTextField combined with a MaskFormatter to accept a maximum 8 digits separated by a decimal point.

    JFormattedTextField textField = new JFormattedTextField();
    MaskFormatter dateMask = new MaskFormatter("####.####");
    dateMask.install(textField);
    

    For a more free-format input (e.g. more digits) you could use a DocumentFilter with a JTextField. Here is an integer filter example

提交回复
热议问题