从TextField JavaFX移除默认焦点 [英] remove default focus from TextField JavaFX

查看:723
本文介绍了从TextField JavaFX移除默认焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经由SceneBuilder在表单中设计了一些TextField,当我运行代码时,默认情况下已单击其中一个TextField,我想在运行代码时,默认情况下未选择任何TextField,并且用户选择了TextFiled.

I have designed some TextField in a form by SceneBuilder, when I run the code, one of the TextFields has been clicked by default, I want when I run the code, none of the TextFields get selected by default and user select a TextFiled.

更新:如您所需要的图像中所示在代码运行时使第一个字段像其他两个字段一样(字段中没有光标)

UPDATE: As you see in this image I want to make the first field like other two field when code runs(no curser in field)

我该怎么做?

推荐答案

由于没有实现此目的的公共方法,因此没有直接的方法.不过,您可以使用技巧来做到这一点.您可以使用BooleanProperty来仅检查控件的首次聚焦时间.监听控件的focusProperty(),当它第一次被聚焦时,将焦点委托给它的容器.对于其余的焦点,它将按预期工作.

As there is no public method to achieve this, there is no direct way. Though, you can use a trick to do it. You can have a BooleanProperty just to check when the control is focused for the first time. Listen to focusProperty() of the control and when it is focused for the first time, delegate the focus to its container. For the rest of the focus, it will work as it should.

示例:

import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        final BooleanProperty firstTime = new SimpleBooleanProperty(true); // Variable to store the focus on stage load
        VBox vBox = new VBox(10);
        vBox.setPadding(new Insets(20));
        TextField t1 = new TextField();
        TextField t2 = new TextField();
        TextField t3 = new TextField();
        t1.setPromptText("FirstName");
        t2.setPromptText("LastName");
        t3.setPromptText("Email");
        vBox.getChildren().addAll(new HBox(t1, t2), t3);
        primaryStage.setScene(new Scene(vBox, 300, 300));
        primaryStage.show();
        t1.focusedProperty().addListener((observable,  oldValue,  newValue) -> {
            if(newValue && firstTime.get()){
                vBox.requestFocus(); // Delegate the focus to container
                firstTime.setValue(false); // Variable value changed for future references
            }
        });
    }

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

在初始屏幕加载时:

这篇关于从TextField JavaFX移除默认焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆