表单验证器消息

时间:2014-05-10 09:34:49

标签: javafx javafx-2 javafx-8

我正在寻找类似于以下示例的表单验证器:

enter image description here

enter image description here

这个自定义JavaFX组件是否可以使用标准JavaFX完成?

我是否有任何示例可以创建类似于这些的表单验证器?

2 个答案:

答案 0 :(得分:16)

为了给你一个启动,这是一个使用ContextMenu的小例子。对于此方案,ContextMenu可能不是理想的控件,您可以将其替换为LabelText等。将TextFieldLabel保留在内一个HBox(最初隐藏Label),HBox进入GridPane。或者,您可以一起使用任何其他方法!

您可以使用CSS设计验证消息/控件!

只是添加(可能你知道这一点):

功能,取决于你,何时你想要触发验证, 你的验证条件是什么。在我的示例中,我正在检查空文本字段,并且我已在登录按钮的单击上触发了验证。您可以在类似方案下触发验证,或者从 TextField 或其他方案中删除焦点触发验证!

您正在寻找各种方法,javafx在UI控件和设计方面非常丰富,完全取决于您的创造力!

<强> ValidationDemo.java

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class ValidationDemo extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Validation Demo");
        BorderPane borderPane = new BorderPane();

        borderPane.setCenter(loadLoginScreen());
        Scene scene = new Scene(borderPane, 700, 500);
        scene.getStylesheets().add(
                ValidationDemo.class.getResource("context.css")
                        .toExternalForm());
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private GridPane loadLoginScreen() {

        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));

        Text scenetitle = new Text("Welcome");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitle, 0, 0, 2, 1);

        Label userName = new Label("User Name:");
        grid.add(userName, 0, 1);

        final TextField userTextField = new TextField();
        grid.add(userTextField, 1, 1);

        Label pw = new Label("Password:");
        grid.add(pw, 0, 2);

        final PasswordField pwBox = new PasswordField();
        grid.add(pwBox, 1, 2);

        Button btn = new Button("Sign in");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        grid.add(hbBtn, 1, 4);

        final Text actiontarget = new Text();
        grid.add(actiontarget, 1, 6);

        // Context Menu for error messages
        final ContextMenu usernameValidator = new ContextMenu();
        usernameValidator.setAutoHide(false);
        final ContextMenu passValidator = new ContextMenu();
        passValidator.setAutoHide(false);

        // Action on button press
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent e) {
                // Clearing message if any
                actiontarget.setText("");

                // Checking if the userTextField is empty
                if (userTextField.getText().equals("")) {
                    usernameValidator.getItems().clear();
                    usernameValidator.getItems().add(
                            new MenuItem("Please enter username"));
                    usernameValidator.show(userTextField, Side.RIGHT, 10, 0);
                }
                // Checking if the pwBox is empty
                if (pwBox.getText().equals("")) {
                    passValidator.getItems().clear();
                    passValidator.getItems().add(
                            new MenuItem("Please enter Password"));
                    passValidator.show(pwBox, Side.RIGHT, 10, 0);
                }
                // If both of the above textFields have values
                if (!pwBox.getText().equals("")
                        && !userTextField.getText().equals("")) {
                    actiontarget.setFill(Color.GREEN);
                    actiontarget.setText("Welcome");
                }
            }
        });

        userTextField.focusedProperty().addListener(
                new ChangeListener<Boolean>() {
                    @Override
                    public void changed(
                            ObservableValue<? extends Boolean> arg0,
                            Boolean oldPropertyValue, Boolean newPropertyValue) {
                        if (newPropertyValue) {
                            // Clearing message if any
                            actiontarget.setText("");
                            // Hiding the error message
                            usernameValidator.hide();
                        }
                    }
                });

        pwBox.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> arg0,
                    Boolean oldPropertyValue, Boolean newPropertyValue) {
                if (newPropertyValue) {
                    // Clearing message if any
                    actiontarget.setText("");
                    // Hiding the error message
                    passValidator.hide();
                }
            }
        });
        return grid;
    }

}

<强> context.css

.root {
  -fx-background-color: cornsilk; 
  -fx-padding: 10;
}

.context-menu {
  -fx-background-color: #006699;
  -fx-text-fill: white;
  -fx-padding: 0;
}

.context-menu:hover {
  -fx-background-color: #006699;
  -fx-text-fill: white;
}

.menu-item .label {
  -fx-text-fill: white;
}

.menu-item:focused .label {
  -fx-text-fill: white;
}

答案 1 :(得分:0)

现在有一个名为JFoenix的库,该库具有带有材质设计的JavaFX节点,它还实现了一些实用程序,例如TextField验证器,但是针对其自己的材质textfield(<div> <form id="myForm1"> <h4> This is the first one I was able to implement.</h4> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes"> <label class="custom-control-label" for="defaultGroupExample1">Yes</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no"> <label class="custom-control-label" for="defaultGroupExample2">No</label> </div> <input class="button" type="button" name="groupOfDefaultRadios" value="Submit"> </form> </div> <div id="myForm1Result" style="display:none"></div> <div> <form id="myForm2"> <h4> This one does not work</h4> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample3" name="groupOfDefaultRadios" value="yes"> <label class="custom-control-label" for="defaultGroupExample2">Yes</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample4" name="groupOfDefaultRadios" value="no"> <label class="custom-control-label" for="defaultGroupExample3">No</label> </div> <input class="button" type="button" name="groupOfDefaultRadios" value="Submit"> </form> </div> <div id="myForm2Result" style="display:none"></div>),其外观如下:

如果需要,您还可以像警告图标一样向其添加图像。

这是您的操作方式:

from vpython import *



display(width = 1300, height = 1000)

drag_coeff = 0.266

projectile = sphere(pos = vector(0,0,0), 
                radius = 5, 
                color = color.red, 
                make_trail = True)

projectile.area = 1.06*10**-4

projectile.speed = 275  #muzzle speed in m/s
projectile.angle = (90*pi)/180 #angle from the x-axis

projectile.velocity = vector(projectile.speed*cos(projectile.angle),
                         projectile.speed*sin(projectile.angle),
                         0)


projectile.mass = 275
grav_field = 9.8
dt = .01
t = 0

while (projectile.pos.y >= 0):

# calculate the force
rate(100)

F_grav = vector(0,-projectile.mass*grav_field,0)
vhat = projectile.velocity / mag(projectile.velocity)
drag_force = 0.5*rho*drag_coeff*projectile.area*mag(projectile.velocity)**2*(-vhat)
force = F_grav + drag_force

#update air density as a function of altitute
rho = (-8.38793939*10**-5)*projectile.pos + 1.225 *dt

#update velocity
projectile.velocity = projectile.velocity + force/projectile.mass * dt

# update position
projectile.pos = projectile.pos + projectile.velocity * dt

# update time 

t = t + dt


print(t)
print(projectile.pos)
print(projectile.velocity)

这里DBIO.successful(...)检查文本字段是否为空,其他验证者为JFXTextFieldJFXTextField validationField = new JFXTextField(); RequiredFieldValidator validator = new RequiredFieldValidator(); validator.setMessage("Input Required"); validationField.getValidators().add(validator); validationField.focusedProperty().addListener((o,oldVal,newVal)->{ if(!newVal) validationField.validate(); }); RequiredFieldValidatorRegexValidator

来源:JFoenix