从TextField JavaFX中删除默认焦点

Yas*_*har 5 javafx textfield scenebuilder

我已经在SceneBuilder中以一种形式设计了一些TextField,当我运行代码时,默认情况下已经单击了一个TextFields,我想在运行代码时,默认情况下没有选择任何TextField,用户选择TextFiled.

更新:正如您在图像中看到的那样,我希望在代码运行时将第一个字段设置为其他两个字段(字段中没有光标)

我怎样才能做到这一点?

der*_*itz 14

在我的情况下,接受的答案是行不通的.但这有效:

我请求在runLater中包含父项的焦点.

@FXML
public void initialize() {

    //unfocus pathField
    Platform.runLater( () -> root.requestFocus() );
}
Run Code Online (Sandbox Code Playgroud)

直接调用requestFocuss不起作用.


Hel*_*wag 5

不可编辑的文本字段也有同样的问题,每次都会选择并突出显示该文本字段。

通过设置 myTextField.setFocusTraversable(false); 解决了这个问题

请注意,在这种情况下,焦点将转到下一个 UI 元素,您必须设置您不想聚焦的每个元素。您还无法通过 Tab 键选择元素。

ApiDoc 声明 setFocusTraversable() 默认情况下为 false,但这似乎不起作用,除非明确调用。


Ita*_*iha 4

由于没有公共方法来实现这一点,因此没有直接的方法。不过,你可以使用一个技巧来做到这一点。您可以检查一下BooleanProperty控件何时首次获得焦点。监听focusProperty()控件,当它第一次获得焦点时,将焦点委托给它的容器。对于其余的焦点,它将按其应有的方式工作。

例子:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在初始屏幕加载时:

在此输入图像描述