如何在javafx2中的TextField上的focusOut上打印一些东西

时间:2013-05-16 17:37:11

标签: javafx-2 javafx java java-7 javafx-8

我有一个TextField,想要对textfiels焦点执行一些操作

TextField textField = new TextField();

我该怎么打印

System.ou.prinln("Focus Out");

从文本区域聚焦时。

1 个答案:

答案 0 :(得分:2)

JavaFX 2.2 TextField有一个公开 focusedProperty继承自Node类,只需添加ChangeListener并实施{ {3}}方法。

public class App extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField txt1= new TextField("text 1");
        TextField txt2= new TextField("text 2 ");
        Button btn= new Button("hello");

        StackPane root = new StackPane();
        VBox vBox= VBoxBuilder.create()
                .children(txt1, btn, txt2)
                .build();

        txt1.focusedProperty().addListener(new ChangeListener<Boolean>() {

            @Override
            public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if (t1) {
                    System.ou.prinln("Focus In");
                } else {
                    System.ou.prinln("Focus Out");
                }

            }
        });

        root.getChildren().add(vBox);       
        Scene scene = new Scene(root, 500, 400);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application.
     * main() serves only as fallback in case the application can not be
     * launched through deployment artifacts, e.g., in IDEs with limited FX
     * support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}