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 ||?

Similar Messages

  • How to check validation for a input field?

    For example, I need to check the validation of a field, if OK, then the field will be inputted, otherwise, there will rise a message, how can I implement that?
    Thanks and best regards,
    Anders

    Hi Andres,
    U can write a code in Request Processing--DO_VALIDATE_INPUT
    DATA: LR_BTADMINH       TYPE REF TO   CL_CRM_BOL_ENTITY.
      LR_BTADMINH  ?= ME->TYPED_CONTEXT->BTADMINH->COLLECTION_WRAPPER->GET_CURRENT( ).
        LV_ZZAFLD000057 = LR_ENTITY->GET_PROPERTY_AS_STRING( 'ZZAFLD000057' ).
    IF  LV_ZZAFLD000057 IS INITIAL.
    DATA: L7_MSG_SERVICE TYPE REF TO CL_BSP_WD_MESSAGE_SERVICE,
              LVSP_MSG_V1  TYPE STRING VALUE 'Spare in Progress'.
        L7_MSG_SERVICE = ME->VIEW_MANAGER->GET_MESSAGE_SERVICE( ).
        L7_MSG_SERVICE->ADD_MESSAGE(
            IV_MSG_TYPE       = 'E'
            IV_MSG_ID         = 'ZBSP'
            IV_MSG_NUMBER     = '008'
            IV_MSG_V1         = LVSP_MSG_V1 ).
    ENDIF.
    Regards,
    Lokesh.

  • JTextField input check (errorDialog if invalid) & JComboBox Focus

    I have a JTextfield which does an input check when the JTextField focus listener's focusLost method is called.
    If I loose focus by clicking in on a JComboBox. The check gets done ok and focus is returned appropriately to the JTextField without any problems.
    But if I try to show an errorDialog when the input is incorrect, the focus is returned to the JTextField without any problems, but the JComboBox remains highlighted as though it is still selected!
    I am using sdk 1.4... on a linux box. does anyone know why this happens? and can anyone provide a clean solution to this?
    Thanx,
    Diego Paloschi.

    Hello Kleopatra,
    Here's a little demo:
    import javax.swing.*;
    import javax.swing.event.*;
    public class Debug extends JPanel
    private JTextField t1;
    private JComboBox c1;
    private T1Verifier t1Verifier;
    public void init()
         t1 = new JTextField("20", 10);
         t1.setInputVerifier(new T1Verifier(this));
         String[] s = {"v1","v2","v3"};
         c1 = new JComboBox(s);
         add(t1);
         add(c1);
    public static void main(String s[])
         Debug d = new Debug();
         d.init();
         JFrame f = new JFrame("Debug");
         f.getContentPane().add(d);
         f.setSize(300,300);
         f.setVisible(true);
    class T1Verifier extends InputVerifier
    private Debug debug;
    public T1Verifier(Debug debug)
         this.debug = debug;
    public boolean verify(JComponent input)
         JTextField tf = (JTextField) input;
         float value = Float.parseFloat(tf.getText());
         boolean inRange = (value >= 0) && ( value <= 10);
         return inRange;
    public boolean shouldYieldFocus(JComponent input)
         boolean valid = super.shouldYieldFocus(input);
         JTextField tf = (JTextField) input;
         if ( !valid ) {
         tf.requestFocus();
         JOptionPane d = new JOptionPane();
         d.showMessageDialog(debug, "Out Of Range.", "ERROR" , JOptionPane.ERROR_MESSAGE);
         return valid;
    Even if u comment out the JOptionPane and just make the inputverifier return control to the textfield it still doesn't work! What am I missing? Or how would u doi it?

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

  • How to check whether a batch input session is completed in ABAP program

    I have created a ABAP program to create a batch input session (reference to RSBDCSUB). After the creation of the batch input session, I kick it to start and read the execution log. However, sometimes I cannot read anything from the execution log as the execution of the batch input is a synchronized process to the execution of my program, i.e. at the time being that I try to read the log of a particular transaction, that transaction is being processing / haven't start processing.
    How can I check whether a batch input session is completed in the program?
    The code that corresponding to the triggering of batch input session:
    SUBMIT (SUBREPORT)
       USER MTAB-USERID
       VIA JOB MTAB-GROUPID
       NUMBER JNUMB
       WITH QUEUE_ID  EQ MTAB-QID
       WITH MAPPE     EQ MTAB-GROUPID
       WITH MODUS     EQ 'N'
       WITH LOGALL    EQ LMODUS
    Or is there any method to wait here until the process is completed before further processing?

    Hi gundam,
    1. Or is there any method to wait here until the process is completed before further processing?
    There is no such direct method to wait.
    2. Immediately after submitting in background,
       we cannot wait
      neither can we LOOP and go on detecting
      whether the b/g process has completed or not !
    3. To over come such problems,
      we have to use another technique.
    4. we have to submit another
       job which will get triggered
       on event SAP_END_OF_JOB
       ie. when the original job will finish,
      our new job will AUTOMATICALLY get triggered,
    5. This new job / program
       will do the FURTHER actions !
    regards,
    amit m.

  • Automatic Payment Details/Check Details Required on Input of Posting No

    SAP Version:: SAP ECC 6.0 EHP3 Version.
    Query: We require payment/check details as output from SAP after user is making payment in SAP through Payment Run F110.
    We are having Input Invoice Posting Number(From MIRO or FBV0).
    More Detail:
    Through Payment Run: User can make multiple payments, however invoice are posted one by one.
    So we want to get output from SAP(Payment details and check details) on the input of MIRO/FBV0) posting Number

    Hi Christian,
         Agreed what you said. But in parameters on third tab page that is FREE SELECTION where you can give selection criteria with F4 (Input help) as parameters. Then what happen if account is having multiple line items with different Business area, Profit center,Document No.... here as per your requirement you go to input help select required field name for eg. Doc. No and enter the doc. no. in the below values field eg. 1234567890,0987654321
    now the proposal list generated by APP (F110) is showing line items to pay are those two Doc. No. which we have selected in Input parameters. instead of all line items.
    If we use Profit center As a FREE SELECTION then APP is selecting only those line items which are posted for given Profit Center instead of selecting all items. It is selecting items as per given parameters.
    My concern is i am able to use all FIELDS in FREE SELECTION accept Doc. Date, Posting date, & Due Date..
    I hope this will clarify the scenario
    regards
    Sagar

  • JSF Validation failure causes input values disappear

    I am using a custom validator in my application by creating a class that implements javax.faces.validator.Validator. I use this validator for some input fields. When the validation fails the values that the user has entered are lost. Is their any way that we can keep these values? These input fields are in DataTable.
    - Sandeep.
    Edited by: sgatl2 on Mar 24, 2010 10:41 AM

    If you see the JSF lifecycle, the validation phase comes before the update values phase.
    So if your custome validator fails, the model will not change.
    I would suggest you try with client side validation without a page refresh/server call.

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

  • Can Check Valid From task be run on multiple JVMs in clustered env.

    The configuration screen for the Check Valid From scheduler task allows it to be run oin more than one JVM in a clustered environment.
    Has anyone done this?
    Does this cause any problems?

    Hello Timothy,
    This is not recommended for any scheduler task as it potentially means that the task could be run multiple times and would most likely lead to inconsistencies in the results of the task. Have a look at SAP note 798633 which discussed this a little more.
    Regards,
    Lorcan.

  • Checking/Validating user input in a text field

    How can I validate a user's input in a text field and require them to input it in the following format:
    AAA 9999-999
    (where A can be letters and 9 can be numbers)
    Is there any documentation on how to validate user inputs in this manner?
    Thanks!
    BoilerUP

    Hi,
    Create a validation PL/SQL process, select Function returning Error and use something similar to the example below.
    I tested it but may be I missed something. I used field name P1_TEST.
    DECLARE
    v_number NUMBER;
    v_error VARCHAR2(1000);
    BEGIN
    --check if you have numbers in positions 5-8 and 10-12
    v_number:=SUBSTR(:P1_TEST,5,4);
    v_number:=SUBSTR(:P1_TEST,10);
    --check string length
    IF LENGTH(:P1_TEST)!=12 THEN
    RETURN 'String length must be 12 characters';
    END IF;
    --check if position 4 is empty
    IF INSTR(SUBSTR(:P1_TEST,4,1),' ')=0 THEN
    RETURN 'There should be a space between letters and numbers';
    END IF;
    --check if position 9 has "-"
    IF INSTR(SUBSTR(:P1_TEST,9,1),'-')=0 THEN
    RETURN 'There should be a dash between numbers';
    END IF;
    --check if positions 1-3 has letters
    FOR i IN 1 .. 3 LOOP
    SELECT ascii(substr(:P1_TEST, i, 1)) INTO v_number
    FROM Dual;
    IF v_number>=48 AND v_number<=59 THEN
    RETURN 'Only letters are allowed in positions 1,2,3';
    END IF;
    END LOOP;
    RETURN NULL;
    EXCEPTION
    WHEN OTHERS THEN
    v_error:=SQLERRM;
    IF INSTR(v_error, 'ORA-06502')>0 THEN
    RETURN '...must be integers only';
    ELSE
    RETURN v_error;
    END IF;
    END;
    I hope it will give you an idea on this type of validation.
    Val

  • Message on the check validity of input with "SPRY "

    bonjour,
    Comme mon englais n'est pas bon, je vais faire vite.
    j'utilise "SPRY" pour controler la saise d'un input.
    j'ai bien le message quand la saisie est fausse.
    comment faire si je veux aussi un message quand la saisie est
    bonne ?
    Merci
    Merci google traduction ;)

    Hi Nadin,
    Once you enter YEAR Range in the selection screen, for Ex:., 2000 to 2004,
    you can put a select query as below.
    SELECT Single * from DBTAB into w_dbtab where dbtab-start GT s_gjahr-low
                                                                     and dbtab-end   LT s_gjahr-high.
    If sy-subrc eq 0.
    " you can proceed.
    else.
      " Throw an error message.
    endif.
    If the query returns atleast one value, this means that atleast one date exists and you can display the projects/ contracts for that particular period.
    <b>Reward points for helpful answers.</b>
    Best Regards,
    Ram.

  • JTextField input validation

    hi!
    i have made a input form for my study project.in the form i want that user only can input numeric value.
    another problem is that i want to make my textfield in such a type so that uesr can,t enter more than 20 character.
    please tell me how can i solve these problems.

    You are entering the same question with two different user names, i dont know what you are trying to achieve but i can guarantee you wont get a faster reply to your question if you free post like that. anyway i have answered part of your question to the other post.

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

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

  • Form validation for file inputs

    Hi,
    Does anybody know if Spry can do a file input validation? I'm
    interested at least to check if the file is empty or not.
    Thanks

    is this a JavaScript question or a Java queston ?

Maybe you are looking for

  • How to change an mpeg4 song to a mp3????

    I puchased a few songs lately on i tunes store but they are all in mpeg4 and i cant do nothing with them........ is it possible to change it into an mp3?

  • JavaFX accessing Java Inner Classes

    We have LOTS of common Java classes that look like this... public class X {     public class Y {         public static final String Z = "ZzZZZzzZzzZzzZz"; }So in JAVA we can access them like this... public String z = X.Y.Z;But in JavaFX I CAN'T do th

  • Create folders/tab in A/P Invoice

    How to create folders/tab in marketing documents..I need extra tab next to attachments

  • Speeding up Java Applets

    Hi, We are developing a system that extensively uses Java Applets. But it's taking a lot of time to load up the applets. Is there any way of speeding up the execution of Java Applets? Is Sun working on improvements to JRE that will result in better s

  • Encountered a problem

    I'm not getting the "unknown error" specified in the FAQ article. I get a dialogue box with: iTunes has encountered a problem and needs to close. We are sorry for the inconvenience. Then an option to transmit the issue to Microsoft. I've updated Wind