I have created an animation where prompt text will move up as text to the top of its text field when the field is focused, and move downwards when out of focus. However, if the user clicks too fast ( like keep pressing 'tab'), then the animation will the position of the prompt text will go chaos. How do i fix it?
import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.RowConstraints;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
public class Sing_Up implements Initializable {
@FXML
private TextField textField1;
@FXML
private TextField textField2;
@FXML
private TextField textField3;
@FXML
private TextField textField4;
@FXML
GridPane d;
@FXML
Button button;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
button.setOnAction(event -> {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Home.fxml"));
try {
button.getScene().setRoot(loader.load());
} catch (IOException e) {
e.printStackTrace();
}
});
for (Node node : d.getChildren()) {
System.out.println(node);
// check if the node is a TextField
if (node instanceof TextField) {
TextField textField = (TextField) node;
// apply the animate() method to the TextField
animate(textField);
}
}}
public void animate(TextField textField){
Text promptText;
String p=textField.getPromptText();
// Create a new Text node to represent the prompt text
promptText = new Text(textField.getPromptText());
promptText.setFill(Color.RED);
promptText.setFont(textField.getFont());
GridPane parent = (GridPane) textField.getParent();
GridPane.getRowIndex(textField1);
// Animate the prompt text when the TextField receives focus
textField.focusedProperty().addListener((observable, oldValue, newValue) -> {
// Position the prompt text just above the TextField
if(!parent.getChildren().contains(promptText)&& !(GridPane.getRowIndex(textField) ==null)){
parent.add(promptText,0, GridPane.getRowIndex(textField));}
promptText.setVisible(true);
if (newValue&&textField.getText().equals("")) {
promptText.setVisible(true);
TranslateTransition tt = new TranslateTransition(Duration.seconds(0.3), promptText);
tt.setByY(-35);
tt.play();
} else {
if (!newValue && textField.getText().isEmpty()){
TranslateTransition tt = new TranslateTransition(Duration.seconds(0.3), promptText);
tt.setByY (35);
tt.play();
tt.setOnFinished(event -> {
promptText.setVisible(false);
});};
;
}
;});}}