如何在javafx中自动提交表单

时间:2016-08-24 06:59:21

标签: javafx

我想在javafx中创建一个cbt,如果时间过去,我可能会遇到一个不知道如何自动提交表单的问题,并且可能是其中一个学生尚未完成测试。另外,我想知道如何在javafx中禁用表单

1 个答案:

答案 0 :(得分:2)

只需拨打Node即可停用node.setDisable(true)。由于孩子也会被自动禁用,您也可以为要禁用的Node的父级执行此操作,只要没有其他子项不应被禁用。

使用ScheduledExecutorService

可以轻松实现超时
private ScheduledExecutorService executorService;

@Override
public void start(Stage primaryStage) {
    TextField tf = new TextField();
    Label label = new Label("Your Name: ");
    Button submit = new Button("submit");
    GridPane root = new GridPane();
    label.setLabelFor(tf);

    root.addRow(0, label, tf);
    root.add(submit, 1, 1);
    root.setPadding(new Insets(10));
    root.setVgap(5);
    root.setHgap(5);

    AtomicBoolean done = new AtomicBoolean(false);

    executorService = Executors.newScheduledThreadPool(1);

    // schedule timeout for execution in 10 sec
    ScheduledFuture future = executorService.schedule(() -> {
        if (!done.getAndSet(true)) {
            System.out.println("timeout");
            Platform.runLater(() -> {
                root.setDisable(true);
            });
        }
    }, 10, TimeUnit.SECONDS);

    submit.setOnAction((ActionEvent event) -> {
        if (!done.getAndSet(true)) {
            // print result and stop timeout task
            future.cancel(false);
            System.out.println("Your name is " + tf.getText());
        }
    });

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

@Override
public void stop() throws Exception {
    executorService.shutdown();
}

如果您想在ui中显示时间,Timeline可能比ScheduledExecutorService更合适:

@Override
public void start(Stage primaryStage) {
    TextField tf = new TextField();
    Label label = new Label("Your Name:");
    Button submit = new Button("submit");
    GridPane root = new GridPane();
    label.setLabelFor(tf);

    Label time = new Label("Time:");
    ProgressBar bar = new ProgressBar();
    time.setLabelFor(bar);

    root.addRow(0, time, bar);
    root.addRow(1, label, tf);
    root.add(submit, 1, 2);
    root.setPadding(new Insets(10));
    root.setVgap(5);
    root.setHgap(5);

    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(bar.progressProperty(), 0)),
            new KeyFrame(Duration.seconds(10), evt -> {
                // execute at the end of animation
                System.out.println("timeout");
                root.setDisable(true);
            }, new KeyValue(bar.progressProperty(), 1))
    );
    timeline.play();

    submit.setOnAction((ActionEvent event) -> {
        // stop animation
        timeline.pause();
        System.out.println("Your name is " + tf.getText());
    });

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}