1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package test;
import java.net.URL;
import javafx.beans.binding.Bindings;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.control.TextField;
import javafx.scene.layout.Region;
public final class ClearableTextField extends TextField {
private final Region clearButton = new Region() {
{
setId("clearButton");
getStyleClass().add("clear-button");
setPrefWidth(16);
setPrefHeight(16);
setMouseTransparent(false);
setCursor(Cursor.DEFAULT);
setPickOnBounds(true);
}
};
public ClearableTextField() {
super();
initClearButton();
}
public ClearableTextField(final String text) {
super(text);
initClearButton();
}
@Override
protected void layoutChildren() {
super.layoutChildren();
clearButton.toFront();
final double width = getWidth();
final double height = getHeight();
final Insets insets = getInsets();
final double clearW = clearButton.getPrefWidth();
final double clearH = clearButton.getPrefHeight();
// @todo make that offset a configurable CSS property.
final double clearX = width - insets.getRight() - 2 - clearW;
final double clearY = insets.getTop() + (height - insets.getTop() - insets.getBottom() - clearH) / 2.0;
layoutInArea(clearButton, clearX, clearY, clearW, clearH, 0, HPos.LEFT, VPos.TOP);
}
private void initClearButton() {
clearButton.setOnMousePressed(actionEvent -> setText(""));
clearButton.visibleProperty().bind(Bindings.length(textProperty()).greaterThan(0));
getChildren().add(clearButton);
}
@Override
public String getUserAgentStylesheet() {
final URL cssURL = getClass().getResource("ClearableTextField.css");
return (cssURL == null) ? null : cssURL.toExternalForm();
}
} |
Partager