2 Replies Latest reply: Feb 14, 2013 3:49 PM by 990159 RSS

    Programmatically unfocus a TextField?

    990159
      On my view I only have one editable content: Text in a TextField. The problem is that as a user one never gets rid of the focus (because there is nothing else to focus on), once the TextField is focused. I want to remove the focus from the TextField when the user presses Enter. I know how to react to the Enter key being pressed, but I don't know how to unfocus a control/TextField programmatically?

      I got the hint to use http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#setFocused(boolean), but this method is protected and not public, so I can't call this method from the controller assigned to the view containing the TextField. Is this intended? Is there any other way for unfocusing a control in JavaFX 2?

      Thanks for any hint!

      Edited by: srynoname on 14.02.2013 12:47
        • 1. Re: Programmatically unfocus a TextField?
          shakir.gusaroff
          Hi. The following works for me:
          Call requestLayout for the parent node:

          Sample.fxml
            <?xml version="1.0" encoding="UTF-8"?>
          
          <?import java.lang.*?>
          <?import java.util.*?>
          <?import javafx.scene.*?>
          <?import javafx.scene.control.*?>
          <?import javafx.scene.layout.*?>
          
          <AnchorPane fx:id="anchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="afxml.SampleController">
              <children>
                  <TextField layoutX="126" layoutY="90"  onAction="#handleTextField" fx:id="textField" />
              </children>
          </AnchorPane>
          SampleController.java
             package afxml;
          
          import java.net.URL;
          import java.util.ResourceBundle;
          import javafx.event.ActionEvent;
          import javafx.fxml.FXML;
          import javafx.fxml.Initializable;
          import javafx.scene.control.Label;
          import javafx.scene.layout.AnchorPane;
          
          
          public class SampleController implements Initializable {
              
              @FXML AnchorPane anchorPane;
                  
              
              @FXML
              private void handleTextField(ActionEvent event) {
                 
                  anchorPane.requestFocus();
              }
              
              @Override
              public void initialize(URL url, ResourceBundle rb) {
                  // TODO
              }    
          }
          • 2. Re: Programmatically unfocus a TextField?
            990159
            works for me too, so thank you very much :-)