473,516 Members | 2,711 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 7552
ne*************@hotmail.com (- ions) wrote in message news:<47*************************@posting.google.c om>...
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.google. com>...
ne*************@hotmail.com (- ions) wrote in message news:<47*************************@posting.google.c om>...
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_selection.startsWith("M")) //Not exaclly dummyproof
{
display error dialog message here....
}
Jul 17 '05 #3

"- ions" <ne*************@hotmail.com> wrote in message
news:47*************************@posting.google.co m...

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

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

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

news:<68**************************@posting.google. com>...
ne*************@hotmail.com (- ions) wrote in message news:<47*************************@posting.google.c om>...

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_selection.startsWith("M"))
//Not exaclly dummyproof
{
display error dialog message here....
}


A code snippet using the validation routine I earlier posted:

...
static boolean isValidSkyObjectID(String skyObjectID)
{
...
}
...
public void actionPerformed(ActionEvent evt)
{
// Check contents of field after user has pressed ENTER
if (!isValidSkyObjectID(inputTextField.getText()))
{
// Warn user of input validation problem ...

// * Display a message dialog
JOptionPane.showMessageDialog(null,
"Invalid Sky Object - Must be M1 - M110",
"Data Validation Warning ",
JOptionPane.INFORMATION_MESSAGE);

// * Or, update a status field / area ...
statusField.setText("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.text.DocumentFilter.

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.getDocument().addDocumentFilter( new MFilter() );

Good Luck,
Todd



import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
public class MFilter extends DocumentFilter
{

public void insertString(DocumentFilter.FilterBypass fb,
int offset,
String string,
AttributeSet attr) throws
BadLocationException
{

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

public void remove(DocumentFilter.FilterBypass fb,
int offset,
int length) throws BadLocationException
{

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

public void replace(DocumentFilter.FilterBypass fb,
int offset,
int length,
String text,
AttributeSet attrs) throws
BadLocationException
{
String orig = fb.getDocument().getText(offset,length);
text = text.toUpperCase();
fb.replace(offset, length, text, attrs);
if( !validate( fb.getDocument() ) )
{
if( orig.equals( "" ) )
{
fb.remove(offset,text.length());
}
else
{
fb.replace(offset, length, orig, attrs);
}
}
}
public boolean validate(Document 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*****@bigpond.com> wrote in message news:<fy******************@news-server.bigpond.net.au>...
"- ions" <ne*************@hotmail.com> wrote in message
news:47*************************@posting.google.co m...

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

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


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(int offset, String str, AttributeSet a) throws
BadLocationException 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.google.co m...
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
2286
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...
13
9587
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
3160
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
5600
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...
9
7209
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
10578
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...
2
5461
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,...
0
1754
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...
6
4055
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
7276
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...
0
7182
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...
1
7142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7548
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5714
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5110
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...
0
3267
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3259
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1624
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

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.