TextField error checking

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • - ions

    TextField error checking

    I have created a JComboBox with its Items as a list of "M" numbers ie.
    M1,M2,M3....... throgh too M110 (thes are the messier objects, a
    catolouge of deep sky objects) the user selects of of these and views
    it aswell as infomation. The program also has a JTextFiels which
    allows the user to enter the M number. The problem i have is checking
    that what the user has entered is valid, that being an M followed by 1
    - 110 Nothing else, i thought of checking it against the items in the
    comboBox with itemAt() but i cudnt work out a way of looping through
    them, and using that within the if() Expression.... please help.
  • hiwa

    #2
    Re: TextField error checking

    negative_ions_0 @hotmail.com (- ions) wrote in message news:<4799447d. 0312210507.73cb 102@posting.goo gle.com>...[color=blue]
    > I have created a JComboBox with its Items as a list of "M" numbers ie.
    > M1,M2,M3....... throgh too M110 (thes are the messier objects, a
    > catolouge of deep sky objects) the user selects of of these and views
    > it aswell as infomation. The program also has a JTextFiels which
    > allows the user to enter the M number. The problem i have is checking
    > that what the user has entered is valid, that being an M followed by 1
    > - 110 Nothing else, i thought of checking it against the items in the
    > comboBox with itemAt() but i cudnt work out a way of looping through
    > them, and using that within the if() Expression.... please help.[/color]
    You can use InputVerifier extended class, or, more simply, you can do
    the check in the ActionListener for the JTextField.

    Comment

    • - ions

      #3
      Re: TextField error checking

      HGA03630@nifty. ne.jp (hiwa) wrote in message news:<6869384d. 0312211700.2622 2d12@posting.go ogle.com>...[color=blue]
      > negative_ions_0 @hotmail.com (- ions) wrote in message news:<4799447d. 0312210507.73cb 102@posting.goo gle.com>...[color=green]
      > > I have created a JComboBox with its Items as a list of "M" numbers ie.
      > > M1,M2,M3....... throgh too M110 (thes are the messier objects, a
      > > catolouge of deep sky objects) the user selects of of these and views
      > > it aswell as infomation. The program also has a JTextFiels which
      > > allows the user to enter the M number. The problem i have is checking
      > > that what the user has entered is valid, that being an M followed by 1
      > > - 110 Nothing else, i thought of checking it against the items in the
      > > comboBox with itemAt() but i cudnt work out a way of looping through
      > > them, and using that within the if() Expression.... please help.[/color]
      > You can use InputVerifier extended class, or, more simply, you can do
      > the check in the ActionListener for the JTextField.[/color]

      Thats where my problem lies, im not sure how to acually do the
      checking (its proving harder than i thought it would). It will happen
      with the ActionEvent for a button. All i have at the moment is
      checking that the string starts with M, which is far from what i
      want...

      else if( !input_selectio n.startsWith("M ")) //Not exaclly dummyproof
      {
      display error dialog message here....
      }

      Comment

      • Anthony Borla

        #4
        Re: TextField error checking


        "- ions" <negative_ions_ 0@hotmail.com> wrote in message
        news:4799447d.0 312210507.73cb1 02@posting.goog le.com...[color=blue]
        >
        > I have created a JComboBox with its Items as a list of "M"
        > numbers ie. M1,M2,M3....... throgh too M110 (thes are the
        > messier objects, a catolouge of deep sky objects) the user
        > selects of of these and views it aswell as infomation. The
        > program also has a JTextFiels which allows the user to enter
        > the M number. The problem i have is checking that what the
        > user has entered is valid, that being an M followed by 1 - 110
        > Nothing else, i thought of checking it against the items in the
        > comboBox with itemAt() but i cudnt work out a way of looping
        > through them, and using that within the if() Expression....
        > please help.
        >[/color]

        You basically want to know whether a typed in value is valid i.e. conforms
        to the expected format.

        Code below [suitably modified] could be used to perform format checking in
        your JTextField's ActionListener [i..e. you accept input after ENTER
        pressed, check it with the code below, and either accept or reject the
        data].

        Other approaches also exist - it all depends how much effort you wish to
        apply. The following link may be of help:


        d.html

        I hope this helps.

        Anthony Borla

        // -----------------------------------------------------
        public class TestIsValidSkyO bjectID
        {
        public static void main(String[] args)
        {
        if (args.length != 1)
        {
        System.err.prin tln("Usage: java TestIsValidSkyO bjectID SkyObjectID");
        System.exit(1);
        }

        System.out.prin tln(args[0] + " is "
        + (isValidSkyObje ctID(args[0]) ? " valid" : " not valid"));
        }

        public static boolean isValidSkyObjec tID(String skyObjectID)
        {
        if (skyObjectID.ch arAt(0) != 'M')
        return false;

        short numericSuffix = 0;

        try { numericSuffix = Short.parseShor t(skyObjectID.s ubstring(1)); }
        catch (NumberFormatEx ception e) {}

        if (numericSuffix < 1 || numericSuffix > 110)
        return false;

        return true;
        }
        }

        // ---------------------------------------------


        Comment

        • Anthony Borla

          #5
          Re: TextField error checking


          "- ions" <negative_ions_ 0@hotmail.com> wrote in message
          news:4799447d.0 312212314.e5a35 b0@posting.goog le.com...[color=blue]
          > HGA03630@nifty. ne.jp (hiwa) wrote in message[/color]
          news:<6869384d. 0312211700.2622 2d12@posting.go ogle.com>...[color=blue][color=green]
          > > negative_ions_0 @hotmail.com (- ions) wrote in message[/color][/color]
          news:<4799447d. 0312210507.73cb 102@posting.goo gle.com>...[color=blue][color=green][color=darkred]
          > > >
          > > > I have created a JComboBox with its Items as a list of
          > > > "M" numbers ie. M1,M2,M3....... throgh too M110
          > > > (thes are the messier objects, a catolouge of deep sky
          > > > objects) the user selects of of these and views it aswell
          > > > as infomation. The program also has a JTextFiels which
          > > > allows the user to enter the M number. The problem i
          > > > have is checking that what the user has entered is valid,
          > > > that being an M followed by 1 - 110 Nothing else, i
          > > > thought of checking it against the items in the comboBox
          > > > with itemAt() but i cudnt work out a way of looping through
          > > > them, and using that within the if() Expression.... please help.[/color]
          > > You can use InputVerifier extended class, or, more simply,
          > > you can do the check in the ActionListener for the
          > > JTextField.[/color]
          >
          > Thats where my problem lies, im not sure how to acually
          > do the checking (its proving harder than i thought it would).
          > It will happen with the ActionEvent for a button. All i have
          > at the moment is checking that the string starts with M, which
          > is far from what i want...
          >
          > else if( !input_selectio n.startsWith("M "))
          > //Not exaclly dummyproof
          > {
          > display error dialog message here....
          > }
          >[/color]

          A code snippet using the validation routine I earlier posted:

          ...
          static boolean isValidSkyObjec tID(String skyObjectID)
          {
          ...
          }
          ...
          public void actionPerformed (ActionEvent evt)
          {
          // Check contents of field after user has pressed ENTER
          if (!isValidSkyObj ectID(inputText Field.getText() ))
          {
          // Warn user of input validation problem ...

          // * Display a message dialog
          JOptionPane.sho wMessageDialog( null,
          "Invalid Sky Object - Must be M1 - M110",
          "Data Validation Warning ",
          JOptionPane.INF ORMATION_MESSAG E);

          // * Or, update a status field / area ...
          statusField.set Text("Invalid Sky Object - Must be M1 -
          M110");
          // ...
          }

          // Input ok, do work ...
          // ...
          }
          ...

          You may care to check out the following tutorial for additional help:

          This Swing Java Tutorial describes developing graphical user interfaces (GUIs) for applications and applets using Swing components


          I hope this helps.

          Anthony Borla


          Comment

          • Todd Corley

            #6
            Re: TextField error checking

            Look into javax.swing.tex t.DocumentFilte r.

            It lets you do realtime editing to to changes in the document with out
            worrying about firing yourself into an event loop.

            Below will work for you, just add it like

            yourTextField.g etDocument().ad dDocumentFilter ( new MFilter() );

            Good Luck,
            Todd









            import javax.swing.tex t.AttributeSet;
            import javax.swing.tex t.BadLocationEx ception;
            import javax.swing.tex t.Document;
            import javax.swing.tex t.DocumentFilte r;


            public class MFilter extends DocumentFilter
            {

            public void insertString(Do cumentFilter.Fi lterBypass fb,
            int offset,
            String string,
            AttributeSet attr) throws
            BadLocationExce ption
            {

            fb.insertString (offset, string, attr);
            if( !validate( fb.getDocument( ) ) )
            {
            fb.remove(offse t,string.length ());
            }
            }

            public void remove(Document Filter.FilterBy pass fb,
            int offset,
            int length) throws BadLocationExce ption
            {

            String orig = fb.getDocument( ).getText(offse t,length);
            fb.remove(offse t, length);
            if( !validate( fb.getDocument( ) ) )
            {
            fb.insertString (offset,orig,nu ll);
            }
            }

            public void replace(Documen tFilter.FilterB ypass fb,
            int offset,
            int length,
            String text,
            AttributeSet attrs) throws
            BadLocationExce ption
            {
            String orig = fb.getDocument( ).getText(offse t,length);
            text = text.toUpperCas e();
            fb.replace(offs et, length, text, attrs);
            if( !validate( fb.getDocument( ) ) )
            {
            if( orig.equals( "" ) )
            {
            fb.remove(offse t,text.length() );
            }
            else
            {
            fb.replace(offs et, length, orig, attrs);
            }
            }
            }


            public boolean validate(Docume nt doc )
            {
            boolean retVal = true;

            String text = "";
            try
            {
            text = doc.getText(0, doc.getLength() );
            }
            catch( Exception e )
            {
            }
            int len = text.length();
            if( len > 4 )
            {
            return( false );
            }
            if( len > 1 )
            {
            try
            {
            int val = Integer.valueOf ( text.substring( 1)
            ).intValue();
            retVal = val > 0 && val <= 110;
            }
            catch( Exception exc )
            {
            retVal = false;
            }
            }
            retVal = (text.charAt(0) == 'M' && retVal );
            return retVal;
            }
            }

            Comment

            • - ions

              #7
              Re: TextField error checking

              "Anthony Borla" <ajborla@bigpon d.com> wrote in message news:<fyxFb.613 81$aT.46044@new s-server.bigpond. net.au>...[color=blue]
              > "- ions" <negative_ions_ 0@hotmail.com> wrote in message
              > news:4799447d.0 312210507.73cb1 02@posting.goog le.com...[color=green]
              > >
              > > I have created a JComboBox with its Items as a list of "M"
              > > numbers ie. M1,M2,M3....... throgh too M110 (thes are the
              > > messier objects, a catolouge of deep sky objects) the user
              > > selects of of these and views it aswell as infomation. The
              > > program also has a JTextFiels which allows the user to enter
              > > the M number. The problem i have is checking that what the
              > > user has entered is valid, that being an M followed by 1 - 110
              > > Nothing else, i thought of checking it against the items in the
              > > comboBox with itemAt() but i cudnt work out a way of looping
              > > through them, and using that within the if() Expression....
              > > please help.
              > >[/color]
              >
              > You basically want to know whether a typed in value is valid i.e. conforms
              > to the expected format.
              >
              > Code below [suitably modified] could be used to perform format checking in
              > your JTextField's ActionListener [i..e. you accept input after ENTER
              > pressed, check it with the code below, and either accept or reject the
              > data].
              >
              > Other approaches also exist - it all depends how much effort you wish to
              > apply. The following link may be of help:
              >
              > http://java.sun.com/docs/books/tutor...mattedtextfiel
              > d.html
              >
              > I hope this helps.
              >
              > Anthony Borla
              >
              > // -----------------------------------------------------
              > public class TestIsValidSkyO bjectID
              > {
              > public static void main(String[] args)
              > {
              > if (args.length != 1)
              > {
              > System.err.prin tln("Usage: java TestIsValidSkyO bjectID SkyObjectID");
              > System.exit(1);
              > }
              >
              > System.out.prin tln(args[0] + " is "
              > + (isValidSkyObje ctID(args[0]) ? " valid" : " not valid"));
              > }
              >
              > public static boolean isValidSkyObjec tID(String skyObjectID)
              > {
              > if (skyObjectID.ch arAt(0) != 'M')
              > return false;
              >
              > short numericSuffix = 0;
              >
              > try { numericSuffix = Short.parseShor t(skyObjectID.s ubstring(1)); }
              > catch (NumberFormatEx ception e) {}
              >
              > if (numericSuffix < 1 || numericSuffix > 110)
              > return false;
              >
              > return true;
              > }
              > }
              >
              > // ---------------------------------------------[/color]

              Excellent, just what i wanted, didnt think there would of been much to it! Thanks

              Comment

              • Tony Morris

                #8
                Re: TextField error checking

                You want to create your own Document implementation and override the public
                void insertString(in t offset, String str, AttributeSet a) throws
                BadLocationExce ption method.

                --
                Tony Morris
                (BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
                Software Engineer
                IBM Australia - Tivoli Security Software

                "- ions" <negative_ions_ 0@hotmail.com> wrote in message
                news:4799447d.0 312210507.73cb1 02@posting.goog le.com...[color=blue]
                > I have created a JComboBox with its Items as a list of "M" numbers ie.
                > M1,M2,M3....... throgh too M110 (thes are the messier objects, a
                > catolouge of deep sky objects) the user selects of of these and views
                > it aswell as infomation. The program also has a JTextFiels which
                > allows the user to enter the M number. The problem i have is checking
                > that what the user has entered is valid, that being an M followed by 1
                > - 110 Nothing else, i thought of checking it against the items in the
                > comboBox with itemAt() but i cudnt work out a way of looping through
                > them, and using that within the if() Expression.... please help.[/color]


                Comment

                Working...