使用JavaFX和FXML验证用户输入

时间:2015-06-19 17:49:12

标签: java javafx fxml

使用JavaFX和FXML我想验证用户'当他们点击提交时输入。 查看.fxml文档,您会看到我有2个输入字段,一个用于邮政编码,另一个用于城市名称。我正在从xml文件强制执行NumberTextField.java和CityNameTextField.java,但是如何在用户点击提交时确保它们不是空白的?

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

1 个答案:

答案 0 :(得分:6)

在控制器的initialize方法中,只需执行

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

您也可以使用

直接在FXML文件中执行此操作
  <Button fx:id="btn" text="Submit" 
       disable="${ cityNameTf.text.empty || zipCodeTf.text.empty }"/>