TextField is focusing on a charge of scene

Hey, it's a question simple vey but not be able to achieve is what so ever.

I tried the code,
public class Demo extends Application
{
     
     
     public static void main(String[] args)
     {
          launch(args);
     }
     
     
     
     @Override 
     public void start(Stage stage)
     {
          stage.setTitle("Sample");
          Scene scene = new Scene(new Group(), 450, 250);
          
          
          BorderPane borderPane = new BorderPane();
          borderPane = newScreen();
          
          Group root = (Group)scene.getRoot();
          root.getChildren().add(borderPane);
          stage.setScene(scene);
          stage.show();
     }

     public BorderPane newScreen()
      {
           BorderPane  borderPane = new BorderPane();
           
           GridPane gridPane = new GridPane();
           Label cName = new Label("Company Name");
           Label cAbout = new Label("About");
           Label cContact = new Label("Contact");
           final TextField tCompanyName = new TextField();
           TextField tAbout = new TextField();
           TextField tContactUs = new TextField();
           Button add = new Button("Add");
           
           
           tCompanyName.requestFocus();
              
           gridPane.add(cName, 0, 0);
           gridPane.add(tCompanyName, 1, 0);
           gridPane.add(cAbout, 0, 1);
           gridPane.add(tAbout, 1, 1);
           gridPane.add(cContact, 0, 2);
           gridPane.add(tContactUs, 1, 2);
           gridPane.add(add, 0, 3);
           gridPane.setAlignment(Pos.CENTER);
           borderPane.setCenter(gridPane);
           
           
           return borderPane;
      }

          
     }
I want that whenever the scene is loaded, it should focus on the textField object first 'tCompanyName', but requestFocus() doesn't seem to work. Can someone explain to me why?

Published by: abhinay_a on February 6, 2013 02:53

Try to encapsulate the requestFocus in Platform.runLater call - it can work (he has at least for similar things in the past for me), but I don't know why.

Tags: Java

Similar Questions

  • Change the color of the textfield on focus?

    Hello

    I'm trying to change the color of a textfield on the focus. The idea is to show the initial value ("search... ") gray and move to a stronger color when the user types something into the TextField. I added the 'text field' action to clear the intitial value on focus, but somehow I can't get the color change to work. As far as I understand I need to create a second class with a different color for the textfield value and have to activate this class on focus somehow. But how (sorry, I'm a designer)?

    Thanks a lot for your help.

    Try

    http://StackOverflow.com/questions/2516784/change-text-color-in-text-field

  • find when a TextField has focus and when it loses focus

    Does anyone know how to do this in AS3?

    Thank you!

    Use the FocusEvent class...

    tfield.addEventListener (FocusEvent.FOCUS_IN, tell);
    tfield.addEventListener (FocusEvent.FOCUS_OUT, tell);

    function tell(evt:FocusEvent):void {}
    trace (evt.type);
    }

  • Setting the focus to textfield - cannot type

    I'm trying to use a MouseEvent.CLICK event to set the focus to a TLFTextField and let the user type:

    var textField:TLFTextField = menuField.getTextField ();

    textField.stage.focus = textField;

    textField.setSelection (0,0);

    However, when this code executes, the cursor appears in the textfield, but the user cannot type. What can I do to fix this? A more detailed description below:

    I am applying that has many fields, that the user must fill. The fields are generated dynamically and not always the same number, so I made a movieclip called now and wrote a class so he could manage the feature.

    Now has two areas of text, which are TLFTextFields to the inside of the container MovieClips. The first region, lblFieldName, is the label of the field (for example "name:"). The second is the editable text area lblFieldValue the TLFTextFields are inside containers because I found if I tried to put the lblFieldNametext of now 's manufacturer, it would reset immediately (TextFields are apparently not intitialized until the manufacturer of their parent is over...)

    The size and position of lblFieldValue is defined dynamically depending on the size of lblFieldName. The text in lblFieldValue begins in white until the user enters something. Unfortunately, regardless of the width of the textfield, if the text is empty the user select the textfield by clicking the left edge of it, which is completely unrealistic. My solution has been to add a mouse CLICK event to the set now and try to set the focus to the lblFieldValue TextField. But once again, when the previous code is running it places the cursor but does not allow the user to type. I don't know that I'm missing something simple. Any suggestions?

    Problematic are tlf textfields.  unless you have a good reason to use them, you must use classic text.

  • Focusing on the entrance of type textfield

    On my stage, I have a MC with an entry of type textfield. I have an another MC on stage with control for entry as bold and italic. When my textfield has focus and I click one of the MC buttons control it loses focus. I know I can reset the home with stage.focus but wanted to know if there is a better way. As disable MC to take the focus off the text entry control. I thought that this was not the behavior. I thought that only another control of entry type can steal the focus up to now.

    A mc with a mouse event is as good as a button. If you have a way that works, use it.

  • TextField affecting the caret at the end when losing point on

    Hey everybody,

    I would like to put the caret of a TextField at the end of the text when the textfield loses focus, so that the last part of the name of the file will be shwon and not the first part. I ve tried the following:
    ChangeListener<Boolean> onLooseFocus = new ChangeListener<Boolean>() 
             { 
                  @Override
                  public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) 
                  {
                       if (!newValue.booleanValue()) 
                       {
                            textFieldDateiname.end();     
                                    System.out.println(textFieldDateiname.getCaretPosition()); 
                                    // At this point the caret is at the end and it will show:
                                    //ReadOnlyIntegerProperty [bean: TextField[id=textFieldDateiname, styleClass=text-input text-field], name: caretPosition, value: 76]
                       }
                  }
             };
    This ChangeListener is added to the focusedProperty() of my TextField method
    textFieldDateiname.focusedProperty().addListener(onLooseFocus);
    It not work doesn´t, the circumflex is temporarily at the end of the text field.

    Another question: if it works, I would like to reuse the ChangeListener onLooseFocus for diefferent TextField. So I would like to know which TextField has lost focus. I tried
    observable.getSoruce(); // like it works with keyEvent
    System.out.println(observable); // -> ReadOnlyBooleanProperty [bean: TextField[id=textFieldDateiname, styleClass=text-input text-field], name: focused, value: false]
    If the id of the source of the ChangeEvent is known...

    Any ideas?

    Thank you

    Lukas

    Edited by: 972241 on 20.11.2012 06:08

    For the latter, you can climb the Observable to a ReadOnlyProperty and call getBean() on it; mount the getBean() call results in a TextField.

    I have no good solution for most of your question. It seems that the default behavior is to restore the position of carat at the beginning of the text, and the listener realizes that runs after your custom listener.
    If the best hack I see is to have a flag that replaces the carat position changes. Set the flag to true on loses focus. Register a listener with the position property of carat, and if the flag is set back to carat at the end (and then disabled the indicator).
    If you want to use the headphones on several fields of text, instead of a flag, have a set of textfields which will have their positions carat substituted changes.

    It's really a hack; I'd like to think that there is a better solution.

    import java.util.HashSet;
    import java.util.Set;
    
    import javafx.application.Application;
    import javafx.beans.property.ReadOnlyProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class TestFieldFocusTest extends Application {
    
      @Override
      public void start(Stage primaryStage) throws Exception {
        final VBox root = new VBox();
        final TextField tf1 = new TextField();
        final TextField tf2 = new TextField();
    
        final Set overrideNextCaratChange = new HashSet();
    
        final ChangeListener onLoseFocus = new ChangeListener() {
          @Override
          public void changed(ObservableValue observable,
              Boolean oldValue, Boolean newValue) {
            ReadOnlyProperty property = (ReadOnlyProperty) observable ;
            TextField tf = (TextField) property.getBean() ;
            if (!newValue.booleanValue()) {
              tf.end();
              overrideNextCaratChange.add(tf);
            }
          }
        };
    
        final ChangeListener onCaratChange = new ChangeListener() {
          @Override
          public void changed(ObservableValue observable, Number oldValue, Number newValue) {
            ReadOnlyProperty property = (ReadOnlyProperty) observable ;
            TextField tf = (TextField) property.getBean() ;
            if (overrideNextCaratChange.contains(tf)) {
              tf.end();
              overrideNextCaratChange.remove(tf);
            }
          }
        };
    
        tf1.focusedProperty().addListener(onLoseFocus);
        tf1.caretPositionProperty().addListener(onCaratChange);
        tf2.focusedProperty().addListener(onLoseFocus);
        tf2.caretPositionProperty().addListener(onCaratChange);
    
        Button info = new Button("Show info");
        info.setOnAction(new EventHandler() {
    
          @Override
          public void handle(ActionEvent arg0) {
            System.out.printf("Selection: %s (%d characters). Carat position: %d%n",
                tf1.getSelection(),
                tf1.getSelectedText().length(),
                tf1.getCaretPosition());
          }
        });
    
        root.getChildren().addAll(tf1, tf2, info);
        Scene scene = new Scene(root, 100, 200);
        primaryStage.setScene(scene);
        primaryStage.show();
      }
    
      public static void main(String[] args) {
        launch(args);
      }
    
    }
    
  • Anyone can focus a TableView element properly?

    Run the following code:

    It's a simple TableView... now, try without clicking with the mouse or by using the cursor keys to navigate this TableView using nothing more than the page - up and page-down keys. It does not work. After you select an item with the mouse, or navigate once with the cursor, THEN pg-up/page-down keys work also.

    How can I fix these keys work early?
    package hs.javafx;
    
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.scene.Scene;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TablePosition;
    import javafx.scene.control.TableView;
    import javafx.scene.control.TextField;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class PgDownTableViewTest extends Application {
    
      public static void main(String[] args) {
        Application.launch(args);
      }
    
      @Override
      public void start(Stage primaryStage) throws Exception {
        VBox vbox = new VBox();
        final TableView<Person> tableView = new TableView<>();
    
        for(int i = 0; i < 100; i++) {
          tableView.getItems().add(new Person("John" + i, "Hendrikx" + i));
        }
    
        TableColumn<Person, String> firstColumn = new TableColumn<>("First name");
        TableColumn<Person, String> secondColumn = new TableColumn<>("Last name");
        firstColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
        secondColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
        tableView.getColumns().add(firstColumn);
        tableView.getColumns().add(secondColumn);
    
        final TextField textField1 = new TextField();
        final TextField textField2 = new TextField();
    
        vbox.getChildren().addAll(tableView, textField1, textField2);
    
        Scene scene = new Scene(vbox);
    
    //    scene.focusOwnerProperty().addListener(new ChangeListener() {
    //      @Override
    //      public void changed(ObservableValue arg0, Object arg1, Object arg2) {
    //        System.out.println(">>> focus : " +arg2);
    //      }
    //    });
    
        primaryStage.setScene(scene);
    
        primaryStage.show();
    
        // attempts at given proper focus...
        tableView.requestFocus();
        tableView.focusModelProperty().get().focus(new TablePosition(tableView, 0, firstColumn));
        tableView.focusModelProperty().get().focusBelowCell();
      }
    
      public class Person {
        private StringProperty firstName;
    
        public Person(String firstName, String lastName) {
          setFirstName(firstName);
          setLastName(lastName);
        }
    
        public void setFirstName(String value) {
          firstNameProperty().set(value);
        }
    
        public String getFirstName() {
          return firstNameProperty().get();
        }
    
        public StringProperty firstNameProperty() {
          if(firstName == null) {
            firstName = new SimpleStringProperty(this, "firstName");
          }
          return firstName;
        }
    
        private StringProperty lastName;
    
        public void setLastName(String value) {
          lastNameProperty().set(value);
        }
    
        public String getLastName() {
          return lastNameProperty().get();
        }
    
        public StringProperty lastNameProperty() {
          if(lastName == null) {
            lastName = new SimpleStringProperty(this, "lastName");
          }
          return lastName;
        }
      }
    }

    Select any line by program. Add the following line:

    tableView.getSelectionModel().select(0);
    
  • Gainer Focus and lost Focus

    How implements methods for gainer focus and the focus lost?

    Thank you

    Use a listener changes node.focusedProperty () to find out when a field wins or loses the focus.
    Call node.requestFocus () to request the update (for some reason any I have to wrap it in Platform.runLater so that he can actually do something).
    Call node.setFocusTraversable (false) If you do not want the user to be able to tab to the node, but still be able to click on the node to give it focus.
    Call node.setDisable (true) If you do not want the knot to be active at all.

    I don't know how is calculated the order of focus traversable, maybe the order in which items are added to the scene?
    Not sure how you would create a crossing of focus custom if you need.

      @Override public void start(Stage primaryStage) {
        final TextField tf1 = new TextField("First but not initially focused");
        final TextField tf2 = new TextField("Second initially focused");
        Platform.runLater(new Runnable() { public void run() { tf2.requestFocus(); } });
        final TextField tf3 = new TextField("Can focus by clicking on, but not by tabbing to.");
        tf3.setFocusTraversable(false);
        final TextField tf4 = new TextField("Cannot focus at all.");
        tf4.setDisable(true);
        tf1.focusedProperty().addListener(new ChangeListener() {
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
              if (newValue) {
                System.out.println("First text field gained focus");
              } else {
                System.out.println("First text field lost focus");
              }
            }
          }
        );
    
        VBox root = new VBox(); root.setSpacing(5);
        root.getChildren().addAll(tf1, tf2, tf3, tf4);
        primaryStage.setScene(new Scene(root, 300, 100));
        primaryStage.show();
      }
    
  • tab order, several scenes in the movie

    My file has two scenes. A stage charger and a main stage. At the end of the charger the scene is a start button which is responsible for the main stage. Pretty simple.

    I added the tab controls to each of these scenes, so that only the essential elements respond to tabs. Scene Loader tabs perfectly, but the main scene does not work. Once the main stage is loaded, Flash ignores absolutely all my settings tab order and the tabs in each element of the page.

    However, if I remove the charger, the screen scene perfectly main tabs.

    If I change the order of the scenes so that the main stage load first, and the scene of the charger is just in the background. The main components of the scene perfectly.

    If I put it so that the main screen has a master on the first image to jump on loading sites (which is now second in the order of loading), the main stage of the tabs perfectly, but tabs scene Loader through all the elements and does not take into account my tab settings.

    Near as I can understand, Flash does not settings on the tab to exist for any beyond the first stage in the load order. It is the case, or am I just missing something here? Also, I put the tab settings using the accessibility Panel in CS3.

    scenes were simply implemented to help you organize the workflow and have been buggy from the beginning, when you use Actionscript... They had to be removed a long time ago. You can set the tabIndex property, which is a public property of the InteractiveObject, objects with Actionscript class, starting with 0 and moving upward... do not the same index to several items

  • Fuzzy camera image-update?

    I can't get the camera to focus well any resolution or "scene" I select.

    I cleaned the lens of the camera with a spray of cleaning for glasses and still no joy.

    That is what I'm missing that will get back my phone camera, focusing properly and

    Get sharp images every time?

    Press and hold the camera button until the square becomes green and then release the camera button. It is the autofocus function.

  • help filter the alphabets?

    if(key==Characters.LATIN_SMALL_LETTER_A)
            {
                if(CharacterUtilities.isLetter(key))
                {
                    redText("a");
                }
            }
    
    public void redText(String str)
        {
            text=new TextField(Field.FOCUSABLE|TextField.NO_NEWLINE)
            {
                public void paint(Graphics g)
                {
                    g.setColor(Color.RED);
                    super.paint(g);
                }
            };
            text.setText(str);
            add(text);
        }
    

    Hello

    If the user enters an alphabet (a - z A - Z) in the textfield text should be red.

    I tried to code above.

    But if I use it I have to do too much coding.

    is there anyway that I can do it with a minimum of coding.

    Try this

    TextField textField = new TextField(){
    
                        protected void paint(Graphics g) {
                            int oldColor = g.getColor();
                            String text = getText();
                            char ch;
                            int x = 0;
                            for (int i = 0; i < text.length(); i++) {
                                ch = text.charAt(i);
                                if(CharacterUtilities.isLetter(ch)){
                                    g.setColor(Color.RED);
                                }else{
                                    g.setColor(oldColor);
                                }
                                g.drawText(ch, x, 0, DrawStyle.LEFT, getWidth());
                                x +=Font.getDefault().getAdvance(ch);
                            }
                        }
                    };
                    add(textField);
    
  • Capturing keyboard events?

    How is it possible to listen to keyboard events, as the depressed return key?  I understand the class ReturnKeyType does not yet work for the QNX InputText component, but even when it's that I'm not sure it will include keyboard events or if it will just be a Visual change to the BACKSPACE on the keyboard.

    I intend using the class flash.text.TextField (for portability) instead of qnx.ui.text.InputText.  Currently, the keyboard will activate and disappear the flash.text.TextField receives or loses the focus.  However, these text fields are the fields of data entry, so I would listen to the back of the key on the keyboard so that I may as well save entered data and remove the keyboard of the screen - or perhaps more simply, just leave the text field to listen to when it loses focus to save the data and allow the keyboard to disappear.  But how do I activate either by pressing back on the keyboard?

    Hey David,

    You can achieve this by using a listener to listen to the keys on your input object as a textfield and response following which keys are pressed. in your case you would listen for the Enter key and perform your actions like taking the focus and the keyboard on the screen. You can use the program below as a reference as to how this can be done:

    package
    {
        import flash.display.Sprite;
        import flash.display.StageAlign;
        import flash.display.StageScaleMode;
        import flash.events.KeyboardEvent;
        import flash.text.TextField;
        import flash.text.TextFieldAutoSize;
        import flash.text.TextFieldType;
        import flash.ui.Keyboard;
    
        [SWF(width="1024",height="600",backgroundColor="#CCCCCC",frameRate="30")]
        public class TextFieldTest extends Sprite
        {
    
            private var myInput:TextField;
    
            public function TextFieldTest()
            {
                super();
    
                // support autoOrients
                stage.align = StageAlign.TOP_LEFT;
                stage.scaleMode = StageScaleMode.NO_SCALE;
    
                myInput = new TextField();
                myInput.width = 300;
                myInput.height = 50;
                myInput.type = TextFieldType.INPUT;
    
                /*
                 * listen for what keys are being pressed and react with
                 * onKeyDown function
                */
                myInput.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    
                addChild(myInput);
    
            }
            private function onKeyDown(e:KeyboardEvent):void
            {
                /*
                 * You can listen for any key presses under the
                 * flash.ui.Keyboard class. it has all the constants
                 * such as .ENTER, .END, etc
                */
                if (e.keyCode == Keyboard.ENTER)
                {
                    trace("You just entered");
    
                    /*
                     * Steal focus away from the textfield object
                     * focus can be set to anywhere and the keyboard
                     * will disappear
                    */
    
                    stage.focus = null;
    
                    /*
                     * Perform other actions such as saving data
                    */
                }
            }
    
        }
    }
    

    hope that helps. Good luck!

  • Difficulties of keyboard shortcut

    I don't know what to do about...  If my component implements IFocusManagerContainer, I can tab from field to field.  If he implements IFocusManagerComponent, keyUpHandler is called, so I can handle keyboard shortcuts.  But they are mutually exclusive - I can't have both.  Tab works or keyUpHandler works.  Implements two interfaces still keeping work tab.  How can I get both of these rather simple features to work at the same time?

    A container (like the app) should not normally be an IFocusManagerComponent

    because there never really developed, her children as the TextInputs

    expected.

    Keyboard events propagate, so once a TextInput has focus, they keyDownHandler

    must be called in the application.

    If nothing only a keyboard events focus are distributed from the scene, then you

    must also listen to here.

  • Application of switch statement

    Hello

    I'm writing a Switch statement that, when executed, should the head of reading either forward or backward a few images in Flash. The switch itself statement shall be effective after a RFID card is analyzed through a RFID reader dongle.

    Here is my code so far:

    // this bit places cursor in textfield.
    stage.focus = rfidValue;
    var tempRFIDValue:String;
    
    rfidValue.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    
    // when the rfid is read it automatically hits Enter afterwards - function is waiting that to happen.
    function keyDownHandler(event : KeyboardEvent) : void {
         if (event.keyCode == Keyboard.ENTER){          
              //Do something here
              
              tempRFIDValue = rfidValue.text;
              trace(tempRFIDValue);
              
         }
    }
         
    
    // With Switch - how to tell it to go from midtobad & midtogood?
    // For example:          use 1st Case (41003dc8d1) as Cabbage - midtogood
    //                         & 2nd Case (41003daf7c) as Oranges - midtobad
    // stop()
    // switch is now listening out for the original function and calling on it (afaik)
    switch (tempRFIDValue){
    
    case "41003dc8d1":
         trace("This is card one");
         
         break;
    
    // case "41003daf7c":
    // trace("Card2");
    // break;
    
    // case "41003d2527":
    // trace("Card3");
    // break;
    
    // case "41003dd538":
    // trace("Card4");
    // break;
    
    // case "41003dcfb6":
    // trace("Card5");
    // break;
    
    // case "010a5c92ec":
    // trace("Card6");
    // break;
    
    // case "41003d76e8":
    // trace("Card7");
    // break;
    
    }
    

    Any help or advice would be greatly appreciated

    If you use something like: gotoAndStop ("Medium"); you don't need to trigger the animation you intend, then simply place these lines of code in the case of switch...

    Switch (cardValue) {}
    case '41003dc8d1 ':
    trace ("btnSpuds");
    gotoAndStop ("Medium");
    break;

    case '41003daf7c ':
    trace ("btnOranges");

    gotoAndStop ("MediumLarge");
    break;

    etc.

  • Find the child's location in the coordinate space of the parent

    I created a map of the counties of Montana.  Each county is an MC inside separate the largest parent movie clip (allcnt_mc).

    When the user clicks on a County, I would like to focus this country on the scene and the zoom to its measurement.

    The hard part has said the parent (allcnt_mc) where the tween to.  Given that each individual County is a child of the parent, they have their own coordinate space with reference to the parent.

    Is there a way I can query the location (x, y) of a child in the coordinate space of the parent?  With this issue, I could calculate the distanct between the point of current regulation of the parent and the child, indicating the distance that the parent will have to move to focus on the scene.  I tried to use localToGlobal but could not understand how to use it.

    //calculate the stage's center
    var stagecentx:Number=stage.width/2
    var stagecenty:Number=stage.height/2
    
    function tweento(e:MouseEvent):void{
         // the first two variables are referncing the county that was most recently clicked on
         var calledx:Number=allcnt_mc[xmlData.row.NAME[e.currentTarget.ivar]].x;
         var calledy:Number=allcnt_mc[xmlData.row.NAME[e.currentTarget.ivar]].y;
         // these variables represent the current location of the stage
         var allcntx:Number=allcnt_mc.x;
         var allcnty:Number=allcnt_mc.y;
         //  I'd like to then tween the allcnt_mc to the location of (calledx,calledy)
         //  but in the coordinate space of allcnt_mc
    
    
    
    

    var pt:Point = new Point (parent.child.x, parent.child.y);

    PT = parent.localToGlobal (PT);

    PT now has the parent.child coordinates in space of the parent coord.

Maybe you are looking for