简体   繁体   中英

Validating User Input using JavaFX and FXML

Using JavaFX and FXML I want to validate users' input when they hit submit. looking at the .fxml doc, you'll see that I have 2 input fields one for zip code and one for cityname. I am enforcing NumberTextField.java and CityNameTextField.java from the xml file, but how can I make sure they are not blank when user hit submit?

FXMLDocument.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import validatetextfieldsfxml.custom.*?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label layoutX="173.0" layoutY="89.0" text="ZipCode" />
      <Label layoutX="173.0" layoutY="118.0" text="CityName" />
      <NumberTextField fx:id="zipCodeTf" layoutX="257.0" layoutY="84.0" />
      <CityNameTextField fx:id="cityNameTf" layoutX="257.0" layoutY="113.0" />
      <Button fx:id="btn" layoutX="217.0" layoutY="162.0" mnemonicParsing="false" text="Submit" />
   </children>
</Pane>

CityNameTextField.java

package validatetextfieldsfxml.custom;

import javafx.scene.control.TextField;
public class CityNameTextField extends TextField {

   public CityNameTextField(){
       this.setPromptText("Enter Your CityName");
   }

   @Override
   public void replaceText(int i, int il, String string){
       if(string.matches("[a-zA-Z]") || string.isEmpty()){
          super.replaceText(il, il, string);
       }
   }

    @Override
    public void replaceSelection(String string) {
        super.replaceSelection(string); 
    }



}

NumberTextField.java

package validatetextfieldsfxml.custom;
import javafx.scene.control.TextField;

public class NumberTextField extends TextField{
    public NumberTextField(){
        this.setPromptText("Enter Only numbers");
    }
    @Override
    public void replaceText(int i, int il, String string){
        if(string.matches("[0-9]") || string.isEmpty() ){
            super.replaceText(i, il, string);
        }
    }

    @Override
    public void replaceSelection(String string){
        super.replaceSelection(string);
    }
}

In your controller's initialize method, just do

btn.disableProperty().bind(zipCodeTf.textProperty().isEmpty()
    .or(cityNameTf.textProperty().isEmpty()));

You can also do this directly in the FXML file with

  <Button fx:id="btn" text="Submit" 
       disable="${ cityNameTf.text.empty || zipCodeTf.text.empty }"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM