473,599 Members | 3,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.
Jul 17 '05 #1
7 7569
ne************* @hotmail.com (- ions) wrote in message news:<47******* *************** ***@posting.goo gle.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 can use InputVerifier extended class, or, more simply, you can do
the check in the ActionListener for the JTextField.
Jul 17 '05 #2
HG******@nifty. ne.jp (hiwa) wrote in message news:<68******* *************** ****@posting.go ogle.com>...
ne************* @hotmail.com (- ions) wrote in message news:<47******* *************** ***@posting.goo gle.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 can use InputVerifier extended class, or, more simply, you can do
the check in the ActionListener for the JTextField.


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....
}
Jul 17 '05 #3

"- ions" <ne************ *@hotmail.com> wrote in message
news:47******** *************** **@posting.goog le.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/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;
}
}

// ---------------------------------------------
Jul 17 '05 #4

"- ions" <ne************ *@hotmail.com> wrote in message
news:47******** *************** **@posting.goog le.com...
HG******@nifty. ne.jp (hiwa) wrote in message

news:<68******* *************** ****@posting.go ogle.com>...
ne************* @hotmail.com (- ions) wrote in message news:<47******* *************** ***@posting.goo gle.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 can use InputVerifier extended class, or, more simply,
you can do the check in the ActionListener for the
JTextField.


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....
}


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:

http://java.sun.com/docs/books/tutor...textfield.html

I hope this helps.

Anthony Borla
Jul 17 '05 #5
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;
}
}
Jul 17 '05 #6
"Anthony Borla" <aj*****@bigpon d.com> wrote in message news:<fy******* ***********@new s-server.bigpond. net.au>...
"- ions" <ne************ *@hotmail.com> wrote in message
news:47******** *************** **@posting.goog le.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/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;
}
}

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


Excellent, just what i wanted, didnt think there would of been much to it! Thanks
Jul 17 '05 #7
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" <ne************ *@hotmail.com> wrote in message
news:47******** *************** **@posting.goog le.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.

Jul 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2290
by: C. Armour | last post by:
Help me, I'm suffering! Situation: I have a load() function which loads a bunch of TextFields with values. There are TextListeners registered for each of these TextFields. Thus, changing the text in any of them fires off a TextEvent, even if done programmatically (by means of setText()). The problem: I need all the various TextEvents fired off during the load operation (as a result of using TextField.setText())
13
9603
by: Stumped and Confused | last post by:
Hello, I really, really, need some help here - I've spent hours trying to find a solution. In a nutshell, I'm trying to have a user input a value in form's textfield. The value should then be assigned to a variable and output using document.write. (Note, there is no submit button or other form elements. Basically
1
3171
by: Suresh | last post by:
How do I insert a char into the textfield on the keypress event of another textfield? I have two textboxes, "text1" and "text2". Important: "text1" is outside the table. "text2" is inside the table cell. On the keydown/keypress/keyup event of "text1", the character which I entered in the "text1" must display in the textfield "text2".
3
5606
by: Sidney Linkers | last post by:
Hi, I'm trying to make a calculated text field in a query where the textvalue is being populated from multiple records. I already use a VBA function to loop through records and concatenate the text. It works but the performance is really bad. I'm looking for a solution in plane SQL, so the looping is done by joining tables. I can't get it to work....
9
7214
by: John Devlon | last post by:
Hi, I would like to check if a text field is empty; I'm using this code ... Dim strTitle As String = String.Empty Try strTitle = Trim(txtTitle.Text) Catch ex As Exception When strTitle = String.Empty MessageBox.Show("error")
9
10657
by: learning | last post by:
Hi! Here's my situation: I have one textfield with one 'submit' button in PAGE1.PHP. When I click on the 'submit' button I am sent to PAGE2.PHP where I have a "switch" routine that checks which 'submit' button was clicked and directs which instructions to do next. My Problem is this: On PAGE1.PHP, there is only one textfield. After filling in the textfield, most of the time people press the 'ENTER KEY' instead of clicking the submit...
2
5467
jkmyoung
by: jkmyoung | last post by:
I was trying to create an applet with a TextField that would only accept an integer, and ignore any other keystrokes. Eg, if a user typed in an 'f' into the field, the TextField should ignore it, and not even put the f into the textbox. However, the TextField does not appear to update until one keypress after I need it to. Eg. if I typed, 10fg, it would end up as "10f" then after the g, become "g10". I'm currently using the keyPressed...
0
1761
by: adamselearning | last post by:
Hi... I've followed Colin Moock's AS3 notes to create a VirtualPet I've got it working from the code at: http://www.adobe.com/devnet/actionsc...n_moock_f6.pdf ...but am now trying to add a textField on the stage that will display the % of calories remaining. Extra code I have created in VirtalPet.as: 1. private var petView (An instance of VirtualPetView) 2. petView.displayInfo() (Called from the digest() method, which is called by...
6
4058
by: simon2x1 | last post by:
i want an inputed value that a user enter into the textfield should remain after clicking submit and an error message display that invalued email.the email textfield will be blank why the other textfield will still display the inputed value
0
7992
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7904
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8398
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
5850
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5438
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3940
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2414
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1505
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1250
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.