【发布时间】:2017-05-23 17:16:01
【问题描述】:
在我的公司,我们的任务是实现一个可自动扩展的文本字段。 由于默认情况下不提供此功能,我们不得不从头开始开发它。网络上有很多可能性,如何实现它,但没有人适合,所以我们决定把我们的代码放在 SO 上,这样其他开发人员也可以使用它。 由于无法扩展文本字段,因此解决方案基于文本区域:
public class TextFieldExpandable extends TextArea {
private final double DEFAULT_HEIGHT = 17.0;
public TextFieldExpandable() {
setMinHeight(DEFAULT_HEIGHT);
setPrefHeight(DEFAULT_HEIGHT);
setMaxHeight(DEFAULT_HEIGHT);
disableEnter();
}
@Override
protected void layoutChildren() {
super.layoutChildren();
setWrapText(true);
setPadding(new Insets(0, 0, 0, 0));
ScrollPane scrollPane = (ScrollPane)lookup(".scroll-pane");
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setPadding(new Insets(0, 0, 0, 0));
StackPane viewport = (StackPane) scrollPane.lookup(".viewport");
viewport.setPadding(new Insets(0, 0, 0, 0));
Region content = (Region) viewport.lookup(".content");
content.setPadding(new Insets(-1, 1, 0, 1));
Text text = (Text) content.lookup(".text");
text.textProperty().addListener((property) -> {
double textHeight = text.getBoundsInLocal().getHeight();
if (textHeight < DEFAULT_HEIGHT) {
textHeight = DEFAULT_HEIGHT;
}
textHeight = textHeight + 1;
setMinHeight(textHeight);
setPrefHeight(textHeight);
setMaxHeight(textHeight);
});
}
private void disableEnter() {
setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
event.consume();
}
}
});
}
}
希望对你有帮助:)
【问题讨论】: