문제

How can i let user write only one number in text field? Other should be consume.

I have code for write number.

private boolean number(char zn){
    if(zn>='0' && zn<='9')
        return true;

    return false; 
    }
도움이 되었습니까?

해결책

You state that this is a Swing question, and so I assume that you are using a JTextField. If so, you have one of two possible solutions here:

  • Use a JFormattedTextField and use a MaskFormatter, something simple like "#" should probably work perfectly here.
  • Or get the JTextField's Document and set its DocumentFilter with one that restricts input to as you deserve it. I think that this would be unnecessarily complex for you, and I recommend the first option.

Check the tutorial on how to use JFormattedTextFields which you can find here: JFormattedTextField Tutorial. It will explain all of the above including how to use a mask formatter with JFormattedTextFields.


Also please check Jon Skeet's blog on Writing the Perfect Question. Writing questions on this and other sites is a learned skill which can get better with study and effort. The tips that this blog contains will help you so that you'll know what information to include in your question so that the volunteers helping you don't have to guess at things. They will appreciate it, and you'll likely get better and quicker answers.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top