JTextField Number Input

Hello.
How do you limit the number of characters in a JTextField.
For example: JTextField first_box_serial=new JTextField(4);
Will still allow the user to inter as many characters in the field.
I want the user to only be able to enter 4 characters and thats it!!
Thank You in advance!!

Use this:
public class LimitedLengthDocument extends javax.swing.text.PlainDocument {     
     int maxLength;
     public LimitedLengthDocument(int maxLength) {
          super();
          this.maxLength = maxLength;
     public void insertString(int offset, String str, AttributeSet a)
          if(getLength() < maxLength)
              super.insertString(offset,str,a);
}Use setDocument(new LimitedLengthDocument(4)); on your JTextField. You'll only be able to type in 4 characters. To only allow numbers you can just modify insertString to check that str is numbers.
Jeff

Similar Messages

  • How to make jTextField 's input unscrollable?

    Dear All
    i create a JTextField, i want to set it inputsize = 5(charaters)
    i am doing like this
    JTextField jTextField = new JTextField(5);
    jTextField.setScrollOffset(0);
    but it doesnot work out
    it is still scrollable, i main i could input more than
    5 charaters
    How to fix JTextField's input size?
    Thx in advance

    Hi,
    that does not change the amount of characters, you can input, it only says, that the JTextFields-size should be 5 times as wide as an average char.
    If you want to limit the characters you will have to replace the Plaindocument JTextFields uses internally with a subclass of it, that overwrites its insertString(...)-method. An example, that makes all input upcase is found in the documentation of JTextField. You can do your checking in a similar way there - just checking if the length of the string to insert plus the length of the text that is currently in the box is greater than the maximum length - if it is not, pass all parameter simply to the super.insertString(...)-method - if it is greater, that only do a Toolkit.getDefaultToolkit().beep().
    Also there are many topics dealing with this stuff - please search the forum for it.
    greetings Marsian

  • Using UITextField for number input

    Hi there,
    I´m fairly new to the Objective-C scene. Right now I´m trying to put an application for the iPhone together. There should be some user input in a way that the user inputs some numbers and the program uses the different numbers to calculate an output.
    As far as I have seen into the iPhone SDK there seems to be only the UITextField for the input, but you only get NSString back.
    Is there a different method for number input, something like UINumberField? Or how can I convert the string into something like float or integer?
    I would greatly appreciate if you could make some code examples, you know since +I´m new to the Objective-C scene+.
    Thank you for your help.
    Dietmar, Ulm, Germany

    Thank you that worked, somehow. I now have a rather complicated changing from string to double, doing the calculation, to number and back to string for the output:
    +NSString *newWeight = textFieldWeight.text;+
    +NSString *newSize = textFieldSize.text;+
    +double newWeightDouble = newWeight.doubleValue;+
    +double newSizeDouble = newSize.doubleValue;+
    +double calc = newWeightDouble /= newSizeDouble;+
    +NSNumber *calcNum = [[NSNumber alloc] initWithDouble:calc];+
    +NSString *calcText = calcNum.stringValue;+
    It does work, but I would prefer, let´s say: a rather smoother way.

  • Search employee details from Business partner number input

    Dear friends
    I am searching employee details by having input as a business partner number from infotype 0000. as pernr has only 8 character in size and bp in 10 char in size. would you please tell me how we can access employee detais from business partner number.
    p.s : I am doing this in CRM system
    Business partner  ?->infotype(0000)-->?
    Any help will be appreicated.
    Regards
    Naeem

    Dear Naeem,
    as a CRM environment is not able to run at the same sytsem / client with HR, the employee data (e.g. infotype actions (IT 0000)) only is available in a scenario with ALE-distribution from a HR-system.
    In this case the employee data from HR-system will be distributed via idocs (message type HRMD_ABA) to the CRM-system and saved to databases HRP558x [x=0 - 5; 0= IT0000; 1 = IT0001; 2 = IT0002; 3 = IT0006, subtype 1; 4 = IT0009; 5 = IT0105, subtype 0005, 0010, 0020] for the central person (object type CP).
    The activated business partner integration (table T77S0, group HRALX, switch HRAC) will create / update related business partners (relation is saved within table HRP1001, subtype B207) according to the mapping of data during idoc inbound processing (active CRM implementation of a BAdI HRALE00INBOUND_IDOC processed within the function module (FM) IDOC_INPUT_HRMD (stored in table TBD52 for evcode = HRMD).
    Reading specific infotype data of a central person (databases HRP558x) will be done using the FM RH_READ_INFTY.
    Regards,
    Michael

  • Serial Number Input on VL01N screen

    Hi,
    I am facing the following issue on the VL01n screen, when serial number is input for the material using a bar code scanner.
    The problem is, it accepts just one serial number for the material and then closes the screen. The requirement is that if there is more than one material in VL01n and if the serial number is input, then instead of closing the window, it should go to the next serial number field.
    For example, if there are 3 materials in delivery, the serial number is getting fed for the first material and then the serial number window closes out. Is there any way by which the closure of this window is avoided until the serial number is fed for all 3 materials.
    Your help will be highly appreciated.
    Thanks in advance,
    Zaman

    I'm from Brazil and I had a similar problem. I bought an iPhone 4s directely from Online Apple Store here in my country, and everything was ok until then (serial numbers did match). About five months later I had this problem with the power button and I went to an authorized center and claimed for another device. The service was really fast and good.. in about 3 days I had I my new device (that they gave me wrapped in plastic and out of any box ... but it looked brand new.... is that normal?) . I just took my phone e came home satisfied.
    Six months later (still under warranty) my wi-fi just stopped working from day to night. I came back to the same authorized a claimed for another phone and got really surprised when the attendant said "The serial number that is on your phone does not match with the number here in our system" (they had two serial numbers in their system: my first iPhone and the one replaced.. the second was suposed to match, but it didn't) . I told him that this was impossible, cause I didn't leave my phone to any repair or switched to anybody, and explained what happend before. If there was a mistake, it was their mistake .. Nobody checks serial number when receving a new phone (from now on, I will). They probably gave the phone that I was suposed to recieve to another person and I recieved another one, or there was a labeling problem at the factory. When I said that I heard " This is impossible, sir". The fact is that makes me wonder about this new phones that they replace us, are the really new ?  But this is as discussion for another topic. How that particular iPhone was with me was a mistery for them and they took it for investigating my problem.
    However, now since 14/05/2013 I'm without my iPhone and they are still trying to solve my problem.

  • Number Input Validation

    I'm having a lot of trouble validating that only a number within the specified range can be taken as input in this program that calculates payments on a loan. The loops repeat and prompt for correct input IF the values inputted are numbers. I need the program to account for Strings and characters, so that if a string or char is entered in the loan amount, year amount, or interest rate amount, the user is prompted again until a number with no chars or strings present is input. I tried everything; I've changed all of my methods to strings and tried to parse the strings into integers, a waste of about 2 hours; I've tried using exception handling, I cannot get it to work right and there's too much overhead for that anyway. If there was just a static method such as NotANumber (NaN) for primitive types so that I could validate at the same time as I take the <variable>.nextDouble, I wouldn't have a problem. Any help please?
    public class Payment
        private double la;
        private double mir;
        private int yrs;
        private double monthlyPayment;
        Scanner inp = new Scanner(System.in);
        public Payment()     //no argument constructor
            la =  0;
            mir = 0;
            yrs = 0;
        public static double monthlyPayment(double loanAmount, double monthlyInterestRate, int years)
            int months = 12;// *= years;
            double temp = monthlyInterestRate;
            months *= years;
            monthlyInterestRate = monthlyInterestRate * .01;
            monthlyInterestRate /= 12;
            double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1/Math.pow(1 + monthlyInterestRate, months));
            System.out.println("Loan amount: " + loanAmount);
            System.out.println("Yearly interest rate: " + temp);
            System.out.println("Years: " + years);
            System.out.println("Monthly payment: " + monthlyPayment);
            return 1;
        public void input()
            char c = ' ';
            String s = "";
            double loan;
            double monthlyInterestRate;
            int years;
            Scanner in = new Scanner(System.in);
            do
                do
                    System.out.println("Enter loan amount: ");
                    loan = in.nextDouble();
                while(loanAmountFalse(loan));
                setLoanAmount(loan);
                do
                    System.out.print("Enter monthly interest rate: ");
                    monthlyInterestRate = in.nextDouble();
                while(monthlyInterestRateFalse(monthlyInterestRate));
                setMonthlyInterestRate(monthlyInterestRate);
                do
                    System.out.print("Enter years: ");
                    years = in.nextInt();
                while(yearsFalse(years));
                setYears(years);
                monthlyPayment(loan, monthlyInterestRate, years);
            while(continueOK());       
        private boolean continueOK()
            boolean cont = true;
            String s = "";
            char c = ' ';
            Scanner in = new Scanner(System.in);
            do                                   //allows prompt to repeat if 'y' or 'n' is not entered
                System.out.print("Enter 'y' to continue or 'n' to end program:");
                s = in.next();
                s = s.toLowerCase();            //input is not case sensitive
                c = s.charAt(0);
                if(c == 'n')
                    System.out.println("System exiting...");
                    System.exit(0);
            while(c != 'y');
            return true;
        private boolean loanAmountFalse(double loanAmount)
            if(loanAmount < 0)
                System.out.println("Loan amount UNDER 0... error...");
                return true;
            else if(loanAmount > 1000000)
                System.out.println("loan amount OVER 1000000...");
                return true;
            else
                System.out.println("loanAmOK method reached...");
                return false;
        private boolean monthlyInterestRateFalse(double monthlyInterestRate)
            if(monthlyInterestRate < 0)
                System.out.println("ERROR: Interest rate must be over 0...");
                return true;
            else if(monthlyInterestRate > 20)
                System.out.println("Error: Interest rate must be under 20...");
                return true;
            else
                System.out.println("good to go...");
                return false;
        private boolean yearsFalse(int years)
            if(years < 0)
                System.out.println("ERROR: years must be over 0...");
                return true;
            else if(years > 100)
                System.out.println("ERROR: years must be under 100...");
                return true;
            else
                System.out.println("Years ok");
                return false;
        public void setLoanAmount(double loanAmount)
            if(loanAmountFalse(loanAmount))
                System.out.print("Error: loan amount must be greater than 0 and less than $1,000,000.");
            else
                this.la = loanAmount;
        public void setMonthlyInterestRate(double monthlyInterestRate)
            if(monthlyInterestRateFalse(monthlyInterestRate))
                System.out.println("Error: interest rate must be greater than 0 and less than 20.");
            else
                this.mir = monthlyInterestRate;
        public void setYears(int years)
            if(yearsFalse(years))
                System.out.println("Error: years must be greater than 0 and less than 100.");
            else
                this.yrs = years;
    }

    flounder wrote:
    Or wrap a try statement around the call to nextDouble.Or use Scanner.hasNextDouble() to determine if the next token can successfully be parsed as a double.

  • DVDSP: Creating Easter Eggs via Remote Number Input

    In the Star Wars DVDs, you can highlight buttons (such as a THX logo) that seemingly have no target. If you use the remote to input 1138 (11 OR 10+1, enter, 3, enter, 8, enter), however, you're taken to hidden content, such as bloopers, deleted scenes, or dancing Yoda.
    Does anyone know how to do that in DVD Studio Pro? I've searched and searched, and all I've found are "hidden button" tutorials, arguments, on-screen number entry, and so on. Not quite what I'm looking for. From what I can tell, entering a number on my remote takes me to the track that corresponds to that number, and before I can hit enter, the track starts playing. Once the track starts playing, I can't enter in any more numbers.
    Any help would be appreciated!

    Hi Christian - it's done using hidden buttons.
    The buttons can be stacked one on top of the other and then covered over with a logo image. Using the number pad on the handset simply highlights a specific button. Dialling in a sequence of numbers actually moves you to different buttons each time until finally the last button is selected. Pressing enter activates it and the hidden content plays.
    An alternative to numbers is to use the navigation keys... use hidden buttons and then make sure that only one direction for each button goes to the next (correct) button in the sequence. All other directions can be set to go to any standard menu button that the user can see. Stack the hidden buttons one over the other and put a final large button over the top of that.
    Stacking the buttons means that a computer user cannot accidentally 'mouse over' the hidden buttons and if they do what they'll be able to click on is whatever the top-most button allows. You could use the top most button in the same way as Star Wars uses the THX logo - the start point for the Easter Egg hunt.
    Hope this helps :-)

  • 5800 Number input when sending a text

    Hi there
    I just been trying to send a text message by manually inputting the number (rather than select from the contacts) but I dont get the option to do this. I can only get the option of alphabetic keys not number keys. I'm sure I was able to do this previously and accessed it by tapping on the To: section of the screen and to get access to my contact I tapped on the figure of a person.....
    Any ideas??????
    Tks.

    Whilst in a message press on the line next to the "to:" button and it will bring up a text entry screen.
    Whilst in that screen press the "abc" button in the top right corner and select "number mode".
    This is assuming you are using the standard alphanumeric keypad with the phone in the upright position.
    Message Edited by psychomania on 18-Mar-2009 02:28 PM

  • Jtextfield checking input

    hi all, i was wondering what may be the best way to check input. the current method i'm using is to handle the keyTyped event. for example i do not want to allow the user to enter letter "a":
             @Override
                public void keyTyped(java.awt.event.KeyEvent e) {
                    if (e.getKeyChar()=='a') {
                        e.consume();
                    }but the user can still copy and paste the letter into the text field. is there a proper way to check input which occurs into the TextField and acting on it ?

    Pacerier wrote:
    however if i'm right, not all documents have a document filter right?The reality of things is that all Document implementations shipped with the JRE extend AbstractDocument and can take DocumentFilters, so this is a non-issue. Further, Sun will never change the default Document type installed on the various text components, as that would break backwards compatibility.(1)
    If you're super paranoid you can always ensure your Document takes a DocumentFilter like so:
    JTextField field = new JTextField();
    PlainDocument doc = new PlainDocument();
    doc.setDocumentFilter(new MyDocumentFilter());
    field.setDocument(doc);Most of the time people will just code defensively, like so:
    Document doc = textComp.getDocument();
    if (doc instanceof AbstractDocument) {
       AbstractDocument ad = (AbstractDocument)doc;
       // Do AbstractDocument-specific stuff
    }knowing that the conditional should always be true.
    (1) Technically they could, since JTextComponent only refers to its Document by interface, but the reality of it is that they won't, as too much code has been written around text components having PlainDocuments or DefaultStyledDocuments (whichever is appropriate), or at the very least AbstractDocuments.

  • JtextField , mask input and setText() ...

    ... I use two JTextFields on wich i put a LimitedStyle Document in order to only allow the user
    to input dates in a specific format. Unfortunally, this input mask seems to block the setText()
    function of the JTextField. I can't set the Field to the current DateSytem regarding the date format
    i use (the date is in the right format input). Does someone know how to bypass this problem ?
    If needed i can post the code source of the Document.
    Thanks in advance,
    Marc.

    jTextField.getDocument().setText()
    dosen't work because there is no setText(0 method on document.
    instead i am doing this
    Document docm = new ShowDocument(userInput);
    ShowDocument is a class which overrides insertString() method
    import javax.swing.text.PlainDocument;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    public class ShowDocument extends PlainDocument
    String st=null;
    public ShowDocument(String s)
    this.st = s;
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    super.insertString(offs, st,a);
    return;
    this works fine.

  • Can I get the number input from TextField ?

    I have a beginner in J2ME.
    Can I write ...
    tfTime=new TextField("After this","",4,TextField.NUMERIC);
    time=tfTime.getString();
    t=Integer.parselInt(time);
    For my purpose? Or Do you have any suggestion?
    And If I want to show TextBox in the next display.
    It will alarm after this
    20 second
    How can I get number t from TextField to appear in TextBox

    If you want to get the content of a TextField and put it on a TextBox, you dont need to parse it to int.
    Just do this:
    time = tfTime.getString();
    TextBox tBox = new TextBox("", time, ...);
    Ricardo

  • Serial Number Input for FCStudio2

    I just installed Final Cut Studio 2 and everytime I open anyone of the applicatiions it requests my Name and Serial Number. Has anyone else experienced this? How did you solve the problem?

    I'm in Cincinnati. There are appearently a lot of Grimmms out there. Took me a long time to get this name.

  • PC-FAX phone number input

    Is there a way to do this with a Brother MCF-9340CDW that doesn't involve manually entering the number? Currently, I access the Fax window from the Print window, by clicking on the drop-down menu below the Pages: From: lines. I can't even copy and paste from Contacts because the number format with the () is rejected.
    Before getting this printer I used a cheap USB fax-modem that was less than reliable. I accessed it from the PDF drop-down menu, and had full access to my Contacts from that menu. At least I don't have to send faxes frequently, because this is a PITA.
    Thanks for any information anyone can provide.

    Hi,
    If you do not have time to use jQuery but need it asap,
    you can use approach from Denes Kubicek samples:
    http://htmldb.oracle.com/pls/otn/f?p=31517:154
    called Auto Tab Phonenumber      
    Regards,
    Oleg

  • Validating jtextfield has input

    Can someone kindly explain why this seemingly logical construction doesn't work?
    if(txtOperand1.getText()==null)
    JOptionPane.showMessageDialog(this,"nothing in op 1");
    I'm just trying to make a simple calculator that needs to know that something has been entered into the operand fields.
    Thanks!

    Perhaps your test looked like this:if(txtOperand1.getText()=="")? If so, then that would explain why it didn't work. To compare the contents of two String objects you must use their equals() method, like this:if(txtOperand1.getText().equals(""))PC&#178;

  • Need to format a form field to add a "%" after the number

    I am working on a form that will both print for manual fill-in and also electronic fill-in using reader. My issue  is that I need to
    add a "%" symbol after the number input by the user. I can't use the percentage format type because that places a 0.0% in the field
    when no data is entered and I can't have that due to the need to be able to print a blank form for manual fill-in. Is there a simpl
    e way to append the % character after the user input only if data is in fact input and to leave the field empty otherwise?

    I assume you only want the user to input numbers and you've then set the format to number.
    In the textfield properties go to the format tab and set it to custom.
    Enter a custom keystroke script:
    if(!event.willCommit)
    var nChars = event.selEnd - event.selStart;
    var aFull = event.value.split("");
    aFull.splice(event.selStart, nChars, event.change);
    var strFull = aFull.join("");
    event.rc = !isNaN(strFull);
    This will allow user to input numbers only - strings are regarded as user type.
    Go to the validation tab and enter a custom validation script:
    f = event.value;
    if(f) {
        event.value = f + " %";
    If I understood your question correctly, that should do the trick.
    Torben.

Maybe you are looking for