Java controls Digital Input and input length

Source: Internet
Author: User

Problem:

In Java programming, the number of components is often accepted, so you must strictly control the lease to accept only numbers, and the first character cannot be 0

In addition, some components need to control the input length.

However, Java does not have a special numeric text box to specifically accept numbers.

 

 

Solution:

Below, I will use an instance to implement a limited number input box, read the code ......

 

// Amount is the jtextfield component <br/> amount. addkeylistener (New keyadapter () {<br/> Public void keytyped (keyevent e) {<br/> int length = amount. gettext (). length (); // obtain the number of digits of the current number <br/> If (length <2) {// The number of digits is less than two <br/> string num = (length = 0? "123456789": "0123456789"); // defines characters that can be entered as strings <br/> If (Num. indexof (E. getkeychar () <0) // check whether the key character is included in the allowed characters <br/> E. consume (); // if it is not included in the characters that can be entered, the key event is destroyed. <br/>} else {<br/> E. consume (); // if the maximum number of digits is not less than the allowed number, the event <br/>}< br/>} is destroyed });

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.