Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Setting Caret Position in TextField when Field changed

editOrJan 12 2013 — edited Jan 12 2013
Hi,

I'd like to position the curser at the beginning of the textFields text after every entry. I know there is a method "positionCaret". In the example below this does not seem to work when used in a changeListener.

Hints?
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class CaretPositioner extends Application{

	public static void main(String[] args) {
		Application.launch((java.lang.String[])null);
	}

	@Override
	public void start(Stage primaryStage) {

		BorderPane root = new BorderPane();   
		TextField tf = new TextField();
		tf.textProperty().addListener(new CaretChanger(tf));

		root.setCenter(tf);
		Scene scene = new Scene(root);
		primaryStage.setScene(scene);
		primaryStage.show();           
	}

	class CaretChanger implements ChangeListener<String>{

		private TextField tf;

		CaretChanger(TextField tf){
			this.tf = tf;
		}

		@Override
		public void changed(ObservableValue<? extends String> observable,
				String oldValue, String newValue) {
			System.out.println(tf.caretPositionProperty().get());
			tf.positionCaret(0);
		}
	}

}
Edited by: 979705 on 12.01.2013 00:45

Edited by: 979705 on 12.01.2013 00:46
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 9 2013
Added on Jan 12 2013
1 comment
8,077 views