Re: TextField error checking

From: Anthony Borla (ajborla_at_bigpond.com)
Date: 12/22/03


Date: Mon, 22 Dec 2003 08:02:19 GMT


"- ions" <negative_ions_0@hotmail.com> wrote in message
news:4799447d.0312210507.73cb102@posting.google.com...
>
> 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.
>

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/tutorial/uiswing/components/formattedtextfiel
d.html

I hope this helps.

Anthony Borla

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

    System.out.println(args[0] + " is "
      + (isValidSkyObjectID(args[0]) ? " valid" : " not valid"));
  }

  public static boolean isValidSkyObjectID(String skyObjectID)
  {
    if (skyObjectID.charAt(0) != 'M')
      return false;

    short numericSuffix = 0;

    try { numericSuffix = Short.parseShort(skyObjectID.substring(1)); }
    catch (NumberFormatException e) {}

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

    return true;
  }
}

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



Relevant Pages

  • Re: TextField error checking
    ... a catolouge of deep sky objects) the user ... >> selects of of these and views it aswell as infomation. ... > public class TestIsValidSkyObjectID ...
    (comp.lang.java)
  • Re: TextField error checking
    ... > catolouge of deep sky objects) the user selects of of these and views ... > it aswell as infomation. ... The program also has a JTextFiels which ...
    (comp.lang.java)