Validation in JTextField

Hi ,
I have a JTextField, a JComboBox , a JButton , a JList and a JTable in my Frame. I enter a value in JTextField which has to be validated with a constant. Where do u write the validation ?
i have written the validation in focus lost of JTextField.
This causes problem when i click on the jtable or jcombobox. When i click on the combobox after entering a wrong value in the textfield, cursor remains in the jtextfield but i am able selected a value from the jcombobox as well.
Following is the sample code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
public class EnabledTest extends JFrame implements FocusListener
JTextField jTextField1 = new JTextField();
JTextField jTextField2 = new JTextField();
JComboBox jComboBox1 = new JComboBox();
JList jList1 = new JList();
JButton jButton1 = new JButton();
JTable jTable1 = new JTable();
public EnabledTest()
try
jbInit();
addListeners();
catch(Exception e) {
e.printStackTrace();
public static void main(String[] args)
EnabledTest enabledTest1 = new EnabledTest();
enabledTest1.setVisible(true);
enabledTest1.setBounds(0,0,400,400);
public void addListeners()
jTextField1.addFocusListener(this);
jTextField2.addFocusListener(this);
jComboBox1.addFocusListener(this);
jList1.addFocusListener(this);
jButton1.addFocusListener(this);
public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
if(e.getSource() == jTextField1)
jTextField1_validationPerformed(e);
private void jbInit() throws Exception
jTextField1.setText("jTextField1");
jTextField1.setBounds(new Rectangle(49, 39, 144, 38));
this.getContentPane().setLayout(null);
jTextField2.setBounds(new Rectangle(227, 40, 144, 38));
jTextField2.setText("jTextField1");
jComboBox1.setBounds(new Rectangle(52, 115, 141, 34));
jComboBox1.addItem("one");
jComboBox1.addItem("two");
jList1.setBounds(new Rectangle(239, 110, 135, 120));
jButton1.setText("jButton1");
jButton1.setBounds(new Rectangle(56, 187, 127, 29));
jTable1.setBounds(new Rectangle(55, 251, 330, 117));
jTable1.setModel(new DefaultTableModel(3,3));
this.getContentPane().add(jTextField1, null);
this.getContentPane().add(jTextField2, null);
this.getContentPane().add(jComboBox1, null);
this.getContentPane().add(jList1, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jTable1, null);
private void jTextField1_validationPerformed(FocusEvent e)
jTextField1.removeFocusListener(this);
int intValue = new Integer(jTextField1.getText()).intValue();
if (intValue > 100)
JOptionPane.showMessageDialog(this, "Should be < 100");
jTextField1.requestFocus();
jTextField1.addFocusListener(this);
}

It is fairly easy to validate for a range. I added this kind of validation (attached (*)). At any time you may want to set the validity range of your NumericJTextField. I did it as follows:
this.numericTextField.setValidityRange(-999, +999);
I tested and it does work nicely - couldn't fool it.
(*) Is there any holy way to post files without having to cut and paste them as a whole in this doubly holy tab-eater JTextArea :-(
package textfieldvalidator;
* Title: NumericJTextField
* Description: An example JTextFiled that accepts only digits
* Copyright: nobody - use it at will
* Company:
* @author Antonio Bigazzi - [email protected]
* @version 1.0 First and last
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class ValidatorExample extends JPanel {
NumericJTextField numericTextField; // accepts only digit
JTable table;
public ValidatorExample() {
this.setLayout(new BorderLayout());
this.numericTextField = new NumericJTextField("1234X5");
this.numericTextField.setBackground(Color.black);
this.numericTextField.setForeground(Color.yellow);
this.numericTextField.setCaretColor(Color.white);
this.numericTextField.setFont(new Font("Monospaced", Font.BOLD, 16));
this.numericTextField.setValidityRange(-999, +999);
this.table = new JTable(
new String[][] { {"a1a", "b2b", "c3c"}, {"456", "777", "234"}},
new String[] {"Col 1", "Col 2", "Col 3"}
this.add(this.numericTextField, BorderLayout.NORTH);
this.add(this.table, BorderLayout.CENTER);
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new ValidatorExample());
f.setLocation(300, 75);
f.pack();
f.setVisible(true);
// ===================== the meat ============================
// the specialized JTextField that uses a restrictive doc model
class NumericJTextField extends JTextField {
NumericJTextField() {this("", 0);}
NumericJTextField(String text) {this(text, 0);}
NumericJTextField(int columns) {this("", columns);}
NumericJTextField(String text, int columns) {
super(new NumericDocument(), text, columns);
public void setValidityRange(int min, int max) {
((NumericDocument)this.getDocument()).setValidityRange(min, max);
// check what may have been there already (via constructor)
this.setText(this.getText());
// the restricted doc model - non-numbers make it beep
class NumericDocument extends PlainDocument {
protected int minValue = Integer.MIN_VALUE;
protected int maxValue = Integer.MAX_VALUE;
public void setValidityRange(int minValue, int maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
public void insertString(int offset, String text, AttributeSet a)
throws BadLocationException {
// digits only please (or bring your own restriction/validation)
StringBuffer buf = new StringBuffer(text.length());
for (int i = 0; i < text.length(); i++) {
     if (Character.isDigit(text.charAt(i))) {
     buf.append(text.charAt(i));
     } else {
     java.awt.Toolkit.getDefaultToolkit().beep();
super.insertString(offset, buf.toString(), a);
// get the whole "document" back for range validation
while(true) {
String num = this.getText(0, this.getLength());
     if (num.length() == 0) break;
     int value = Integer.parseInt(num);
     if (value >= this.minValue && value <= this.maxValue) {
     break;
     } else {
     // beeep and chop (or whatever reaction for out of range)
     java.awt.Toolkit.getDefaultToolkit().beep();
     this.remove(this.getLength() - 1, 1);
// Note: in insertString, length is 1 when typing, but it can be anything
// when the text comes from the constructor, when it is pasted, etc.
}

Similar Messages

  • How can I put validation for JTextField when gotfocus and lostfocus

    Hi,
    How can I put validation for JTextField when gotfocus and lostfocus ?
    Thanks
    Wilson

    You add a focusListener to the control you wish to monitor. In the focusLost() handler you do whatever, in the focusGained() handler you do whatever.

  • Validating a JTextField having a float or double value.

    Hello,
    I need help in validating a JTextfield which will accept a float or double value because it the deposit field and it shouldn't be of length more than 7 before the decimal and 2 after the decimal.That is it should be of length 10.I have written the following code for the validation.
    txtDeposit.addKeyListener(new KeyAdapter(){
    //Accept only integer value
              public void keyTyped(KeyEvent e){
              char c = e.getKeyChar();
    if((txtDeposit.getText()).length() == 10)
              if (!(Character.isDigit(c)))
              if(!Character.isISOControl(c))
              getToolkit().beep();
              e.consume();
              });//end of txtDeposit*/
    Please help.

    use javax.swing.InputVerifier
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
    import javax.swing.InputVerifier;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class VerifyInput extends JFrame {
        public VerifyInput(){
            super("Input Verifier");
            this.setSize(200, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextField txt = new JTextField();
            txt.setInputVerifier(new CheckInput());
            this.getContentPane().add(txt, BorderLayout.NORTH);
            JButton btnMoveFocus = new JButton("CLick");
            this.getContentPane().add(btnMoveFocus, BorderLayout.SOUTH);
        public static void main(String[] args) {
            VerifyInput f = new VerifyInput();
            f.setVisible(true);
        class CheckInput extends InputVerifier{
            private int lengthBeforeDot = 7;
            private int lengthAfterDot = 2;
            public CheckInput(){
            public CheckInput(int lengthBeforeDot, int lengthAfterDot){
                this.lengthAfterDot = lengthAfterDot;
                this.lengthBeforeDot = lengthBeforeDot;
            public boolean verify(JComponent input) {
                boolean correct = true;
                try {
                    JTextField tField = (JTextField) input;
                    String text = tField.getText();
                    if(text.length() == 0){
                        return true;
                    if ((correct = isDoubleOrFloat(text))) {
                        correct = isFormatCorrect(text);
                } finally {               
                    if(!correct){
                        Toolkit.getDefaultToolkit().beep();
                        System.out.println("Not Correct");
                    }else{
                        System.out.println("Correct");
                return correct;
            private boolean isDoubleOrFloat(String text){
                try{
                    Double.parseDouble(text);
                }catch(NumberFormatException nfe){
                    return false;
                return true;
            private boolean isFormatCorrect(String text){
                int dotIndex = text.indexOf('.');
                if(dotIndex < 0){
                    return text.length() <= lengthBeforeDot;
                String beforeDecimal = text.substring(0, dotIndex - 1);
                if(beforeDecimal.length() >= lengthBeforeDot){
                    return false;
                String afterDecimal = text.substring(dotIndex + 1);
                if(afterDecimal.length() > lengthAfterDot){
                    return false;
                return true;
    }

  • Breaking a focuslost event in validating a JTextfield

    This problem seems to occur often but I have not found a solution. A JTextfield gets its content validated (for example the field must not be blank) when the focus on the field is lost, and retains the focus until the user enters valid data, after which the focus moves to another field. But say the user decides not to proceed with the input and just decides to click a Close or Exit JButton and come back later. Of course each click of the Close button triggers the focuslost validation on the textfield, making it programatically impossible to quit the frame normally. How does one break the focus on the textfield and exit gracefully?

    Yes, that works. In the jtextfieldFieldFocusLost method i included:
    String jcomponent = evt.getOppositeComponent().getClass().getName();
           if (jcomponent.equals("javax.swing.JTextField"))
              ..do the validation
           else
             ..let the Quit button close the form
           }Great answer, many thanks.

  • Check validation of JTextField input

    In my code, I have a JTextField which can only input 0 or 1, I want to check if the input is empty first then if it is 0 or 1. The following is my code:
    if (myJTextField.getText()==""){
    return "empty";
    else if (myJTextField.getText()!="0" && myJTextField.getText() != "1")
    return "not 0 or 1";
    but it does not work, where is the problem?
    Thanks,

    if (myJTextField.getText().length() > 0){
    try {
    int i =
    int i = Integer.parseInt(myJTextField.getText() );
    if((i != 0) || (i != 1)) msg = "wrong
    g = "wrong number";
    else processIt;
    catch etc...I think the logic operator should be && instead of ||?

  • Validation of JTextField to accept negative and positive values

    Hi,
    I have a question. I have a jTable populated with the fieldname
    in the first column and datatype in the second column.
    I would like to place a JTextField component in the frame
    depending on the data type. So, if a row is selected in the table, the
    datatype of that fieldname is retrieved and depending on that data type
    I want a JTextField to be displayed.
    Now, if the data type is of Integer type, I want the JTextfield to
    accepts Integers only(positive). I have created a class that extends JTextfield.
    But, I want the text field to accept negative integers also. Can anyone please guide me ?

    Hi,
    I wrote an extension of JTable that provides better rendering and editing support for:
    Color
    Font
    Locale
    Integer
    int
    Long
    long
    Short
    short
    Byte
    byte
    BigInteger
    Double
    double
    Float
    float
    BigDecimal
    and some more
    To allow only positive values for the type integer you could use:
    JXTable myTable = new JXTable(...);
    myTable.setDefaultEditor(Integer.class, new IntegerCellEditor(0, Integer.MAX_VALUE, <some locale>));The number editors are based on JFormattedTextField.
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JXTable.html
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/IntegerCellEditor.html
    Homepage:
    http://www.softsmithy.org
    Download:
    http://sourceforge.net/project/showfiles.php?group_id=64833
    Source:
    http://sourceforge.net/cvs/?group_id=64833
    For more information about the number fields have a look at he following thread:
    http://forum.java.sun.com/thread.jspa?threadID=718662
    -Puce

  • Validating JTextfield in an Applet

    I am doing a simple assignment for a Java class I am taking. The assignment consists of doing the Tower of Hanoi with just symbols showing the moves of the disks. I have been successful in writing the recursive statement and init() but I am having trouble validating the JTextfield in the applet. I want to validate the entry is only between 1 and 9. Nothing else and no letters. Here is my code at the present time. If anyone could help I would appreciate it.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class HWProblem6_37Hanoi extends JApplet implements ActionListener
    /** Initialization method that will be called after the applet is loaded
    into the browser.*/
    JLabel directions;
    JTextField userInput;
    //attach JTextArea to a JScrollPane so user can scroll results
    JTextArea outputArea = new JTextArea(10, 30);
    //Set up applet's GUI
    public void init()
    //obtain content pane and set its layout to FlowLayout
    Container container=getContentPane();
    container.setLayout( new FlowLayout() );
    JScrollPane scroller = new JScrollPane(outputArea);
    //create directions label and attach it to content pane
    directions = new JLabel("Enter a Integer Between 1 and 9: ");
    container.add( directions );
    //create numberField and attach it to content pane
    userInput = new JTextField(10);
    container.add( userInput );
    //register this applet as userInput ActionListener
    userInput.addActionListener( this );
    container.add (scroller);
    public void actionPerformed(ActionEvent event)
    //Initialize variables
    int number = 0;
    while (number == 0)
    number = Integer.parseInt(userInput.getText());
    if ((number<1) || (number >9))
    userInput.setText(" ");
    number =0;
    showStatus("Error: Invalid Input");
    else
    showStatus("Valid Input");
    tower(number,1,2,3);
    public void tower(int n, int needle1/*source*/, int needle2/*destination*/, int needle3/*free space*/)
    if (n >0)
    tower(n-1, needle1, needle3, needle2);
    outputArea.append(needle1 + " -> " + needle3 + "\n");
    tower(n-1, needle2, needle1, needle3);
    }

    How to Use Formatted Text Fields
    http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html

  • LostFocus Event

    Hi all,
    I am newbie to swings. I am having a problem when validating a JTextField for only characters, i am able to validate for characters and displaying a proper error message using JOptionPane.
    After the error message is displayed i am again keeping the focus back on to the same JTextField, here the error message is displaying repeatively for 4 to 5 times. i am pasting the code below.
    private void txtdaFocusLost(java.awt.event.FocusEvent evt) {                               
            if(validatenumeric(txtda.getText())) {
                txtda.setText("");
                txtda.requestFocus();
        }    and i am writing the code for validatenumeric below:
    public boolean validatenumeric(String num) {
            if(num.length()!=0)
                try {
                    Integer.parseInt(num);
                } catch(Exception e){
                    JOptionPane.showMessageDialog(null, "Enter data in Numeric Format", "Input Error", JOptionPane.ERROR_MESSAGE);
                    return true;
            return false;
        }

    Quit cluttering the forum, you posted this same question 4 minutes ago.
    What is SwingS? I thought this was the Swing forum.
    Use a JFormattedTextField, or add an InputVerifier to the text field.

  • Focus should not be lost on mouse click

    hai,
    i have a problem with validating a jtextfield,
    i wrote a code for that jtextfield,such that if any error occurs while entring the message is shown on focus is gained on to that textfield,even if user tries to move to the next component using tab he should correct the entry only then focus is shown to the next component on pressing tab,but this failed with mouse click,i mean other than tab if he uses mouse and click on the next component it goes to the next componenet without validating the textfield entry.
    so please help me in disabling mouse click event.

    how are you validating it then? Using a focus listener for focuseLost() shouldn't care about tab or mouse clicks.

  • Help - Focuslost is trigered too many time during jtextfield validation.

    Hi all,
    I am designing a form containing multiple fields with field validations.
    The program supposes bring the focus back to that particular field after the error message is displayed. However; the
    error/warning message is displayed infinitely between the two focusLost events of the two Jtextfields when the focus is switched between the two jtextfields. I tried to google it, but there was no success.
    Can anyone tell me why?
    Thanks a lot.
    core code
        private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {                                     
            // TODO add your handling code here:evt.getSource();
            JTextField roomTag=(JTextField) evt.getSource();
             String text = roomTag.getText();
             if (text.length() >= 3) {
                try {
                        Integer.parseInt(text);
                } catch(NumberFormatException nfe) {
                 //    Toolkit.getDefaultToolkit().beep();
    //SwingUtilities.invokeLater(new FocusGrabber(this.jTextField1));
                   JOptionPane.showMessageDialog(null, "It must be a numeric value");
                   //roomTag.requestFocus();
                   jTextField1.requestFocus();
                   //return;
             } else {
                   JOptionPane.showMessageDialog(null, "It must be 3 chars at least");
                   //roomTag.requestFocus();
                    jTextField1.requestFocus();
                    //return;
        private void txtPhoneFocusLost(java.awt.event.FocusEvent evt) {                                  
            // TODO add your handling code here:
            JTextField roomTag=(JTextField) evt.getSource();
             String text = roomTag.getText();
             if (text.length() <= 12) {
                try {
                    Long a=Long.parseLong(text);
                } catch(NumberFormatException nfe) {
                   JOptionPane.showMessageDialog(null, "The phone number must be a numeric value");
                   txtPhone.requestFocus();
                   //roomTag.requestFocus();
                   //jTextField1.requestFocus();
                   //return;
             } else {
                   JOptionPane.showMessageDialog(null, "The phone number must be 12 chars at most");
                    txtPhone.requestFocus();
                   //roomTag.requestFocus();
                    //jTextField1.requestFocus();
                    //return;
                                         Edited by: ehope on Nov 1, 2009 5:14 PM
    Edited by: ehope on Nov 1, 2009 5:18 PM
    Edited by: ehope on Nov 1, 2009 5:21 PM

    A search of the forum on two terms -- focusLost multiple -- came up with some interesting hits: [forum search|http://search.sun.com/main/index.jsp?all=focuslost+multiple&exact=&oneof=&without=&nh=10&rf=0&since=&dedupe=true&doctype=&reslang=en&type=advanced&optstat=true&col=main-all]
    including a bug report and a work-around by camickr.
    Another possible work around is to remove the focuslistener, then re-add it at the end of the focuslistener but via a Swing Timer to delay its re-addition.

  • Validating JTextField for Date Format

    hello,
    everybody.
    i am trying to perform a validation on text field, i.e if the input is in a date format then it will show, other wise it will consume the character.
    please help me out of this problem i am stucked with it.
    waitng for reply. the following is my code.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JTextField(5);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
         public void keyPressed(KeyEvent ke)
              DateFormat df;
              df = DateFormat.getDateInstance();
              df = (DateFormat) ke.getSource();
              if(!(df.equals(date)))
                   ke.consume();
         public void keyReleased(KeyEvent ke)
    }

    hi,
    thanks very much, u gave me great idea.
    according to ur suggestion i used JFormattedTextField as well as SimpleDateFormat, but while giving keyevent i am getting the error,
    so please if possible reply for this.
    the error is
    java.lang.ClassCastException
         at RilJDateField.keyTyped(RilJDateField.java:61)
         at java.awt.Component.processKeyEvent(Unknown Source)
         at javax.swing.JComponent.processKeyEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)and my source code is
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class RilJDateField implements KeyListener
         JFrame frame;
         JPanel panel;
         JLabel label;
         JFormattedTextField text;
         GridBagLayout gl;
         GridBagConstraints gbc;
         Date date = new Date();
         SimpleDateFormat formatter;
         public static void main(String a[])
              new RilJDateField();
         public RilJDateField()
              panel = new JPanel();
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              panel.setLayout(gl);
              label = new JLabel("Only Date Format");
              text = new JFormattedTextField();
              text.setColumns(10);
              formatter = new SimpleDateFormat("dd mm yyyy");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 1;
              gl.setConstraints(label,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 1;
              gl.setConstraints(text,gbc);
              panel.add(label);
              panel.add(text);
              text.addKeyListener(this);
              text.requestFocus();
              frame = new JFrame("RilJDateField Demo");
              frame.getContentPane().add(panel);
              frame.addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent we)
                             System.exit(0);
              frame.setSize(300,300);
              frame.setVisible(true);
         public void keyTyped(KeyEvent ke)
              Date date = (Date) ke.getSource();
              if(!(date.equals(formatter)))
                   ke.consume();
         public void keyPressed(KeyEvent ke)
         public void keyReleased(KeyEvent ke)
    }

  • Help?...JTextField Validation...

    Hello Gurus...
    Here is the code...
    It is the Class for validating real numbers only...
    The problem which I have been facing is that, When I enter "." in the textfield at any other place like//
    [ 1st time I entered in this fashion] 2.365
    [>>
    now i wanna place a dot"." after 6...by deleteing the "." after 2 and inserting it after 6 [i.e;] 236.5
    <<]
    [I get the mesgbox which i have included in this class, saying no more decimals should be placed here]
    'coz only one time a decimal is placed in a real or double number...
    [ this is wrong... 2.36.6] ...[BUT] [ 2.698 is right]...But my class is ensuring that there is only one decimal... But when u just entered a dot and u wanna place it at another place this is cumbersome and I couldn't find a way how to het rid of this problem....plz help///
    import javax.swing.*;
    * Insert the type's description here.
    * Creation date: (7/15/2009 6:32:41 PM)
    * @author: jav
    public class TextFieldForReal extends javax.swing.text.PlainDocument{
    int maxSize;
    JTextField txtField = null;
    int dot = 0;
    * TextFieldFormatter constructor comment.
    public TextFieldForReal(int limit) {
    maxSize = limit;
    * TextFieldFormatter constructor comment.
    public TextFieldForReal(int limit, JTextField txtObj) {
    maxSize = limit;
    this.txtField = txtObj;
    public void insertString(int offs, String str, javax.swing.text.AttributeSet a)
    throws javax.swing.text.BadLocationException {
    if ((getLength() + str.length()) <= maxSize) {
    if (str == null) {
    return;
    char[] upper = str.toCharArray();
    String buffer = "";
    for (int i = 0; i < upper.length; i++) {
    if (Character.isDigit(upper)){
         buffer += upper[i];
    else if( upper[i] == '.'){
              dot++;
              if(dot == 1)
              buffer += upper[i];
              else{
              JOptionPane.showMessageDialog(null, "No more decimal can placed here");
              break;
    if (!Character.isDigit(upper[i]) && upper[i] != '.') {
    JOptionPane.showMessageDialog(null, "Invalid Input");
    txtField.requestFocus();
    break;
    super.insertString(offs, buffer, a);
    } else {
    throw new javax.swing.text.BadLocationException(
    "Insertion exceeds max size of document", offs);
    /*****USAGE of the above class for validation*****/
    JTextField tf = new JTextField();
    TextFieldForReal textFieldForReal = new TextFieldForReal (10, tf);
    tf.setDocument(textFieldForReal);
    Help,
    jav

    you could check if text in your JTextField matcehs
    some regex, for example
    String text = myJTextField.getText();
    boolean isLegalNumber = text.matches("\\d+\\.?\\d*");this code checks if text consists of one or more
    digits, then optionally a dot, and then none or more
    digits again.
    HTHSorry, I didn't tell u that I've to do it with JDK 1.2 ...
    So regex is not included in JDK1.2

  • JTextField Validation

    Hi,
    I have to validate input in JTextField from the users, the validation would be for date, time, numeric field, test field etc...
    does anyone have some code which can help me speed my development process, also any suggestions
    Ashish

    Hi i have read i good solution in Core Java vol 1 ( get it! ).
    You subclass JTextField, and install your own custom Document class.
    In the document class you override insertString(), and there you can put what ever formatting you want, or just reject keys if there not what you want.
    There might be a better way, but this works cool. Works nicely in the MVC way.
    Harley.

  • Jtextfield focus after validation

    I have a JFrame which contains several jtextField objects. There is also one button. Upon clicking of this button I check if any of these jtextfield is null. If it is I show a message box. At this point I want to focus on the first null jtextfield. However when I try to get focus, nothing happens... Below is the code of the button I use. As you can see I have tried to use SwingUtilities.invokeLater(new Runnable() and requestFocus() and also grabFocus(). But none is working... How can I achieve this?
      private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            if (txtUser.getText()+"" == "" ) {
                txtUser.requestFocus();
            else if (jtxtPass2.getText()+"" == "" ){
                System.out.println("I am here");
                SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                jtxtPass2.requestFocus();
                jtxtPass2.grabFocus();
    //            jtxtPass2.requestFocus();
            else if (txtDBName.getText()+"" == ""){
                txtDBName.requestFocus();
            else if (txtPort.getText()+"" == ""){
                txtPort.requestFocus();
            else if(txtMachine.getText()+"" == ""){
                txtMachine.requestFocus();
            else      { 
            jframeload.setDBVariables(txtMachine.getText() + "", Integer.parseInt(txtPort.getText() + ""), txtDBName.getText() + "", txtUser.getText() + "", jtxtPass2.getText() + "");
            this.dispose();
        }       

    After adding the txtUser.getText().trim().length() == 0 it now works. I guess the check was failing and no focus was being requested. Now my code looks like
    if (txtUser.getText().trim().length() == 0 ) {
                txtUser.requestFocus();
                jframeload.jMessage.append("\n Username is a required field. " + getCurrDate());
                jframeload.jMessage.setCaretPosition( jframeload.jMessage.getDocument().getLength() );
            }

  • Validating a single JTextField

    I was wondering how i would stop people adding more than 5 characters into a JTextField, i dont really want a message to come up after, just the code to stop it from happening
    Thanks

    try
      MaskFormatter format = new MaskFormatter("?????");
    catch(java.text.ParseException e)
      e.printStackTrace();
    JFormattedTextField myField = new JFormattedTextField(format);That should do the trick....
    / why the heck didn't they just make a setMaxLength(int x) method???
    Chris

Maybe you are looking for