How to force the caret to be before a suffix

Viewed 42

In JavaFx, I apply a TextFormatter on a TextField to force the caret to be before a suffix (I want to create a degree field, so the suffix is °).

When I launch my application and click on the textfield, I have the following:

enter image description here

I want the carret to be never after °, like this:

enter image description here

Here is my code: HelloAppplication.java:

package com.example.demo;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 320, 240);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

HelloController.java:

package com.example.demo;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;

public class HelloController {
    @FXML
    private TextField input;

    @FXML
    private void initialize() {
        input.setText("°");
        input.setTextFormatter(getSuffix("°"));
    }

    public TextFormatter<String> getSuffix(String suffix) {
        return new TextFormatter<>(pChange -> {
            int maxPos = pChange.getControlText().length() - suffix.length();
            if (pChange.isContentChange()) {
                pChange.setRange(Math.min(pChange.getRangeStart(), maxPos), Math.min(pChange.getRangeEnd(), maxPos));
            } else {
                pChange.setCaretPosition(Math.min(pChange.getCaretPosition(), maxPos));
                pChange.setAnchor(Math.min(pChange.getAnchor(), maxPos));
            }
            return pChange;
        });
    }
}

hello-view.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>

<VBox alignment="CENTER" spacing="20.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/null" fx:controller="com.example.demo.HelloController">
    <padding>
        <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
    </padding>
   <children>
      <TextField fx:id="input" />
   </children>
</VBox>

Have you got a solution ?

0 Answers
Related