JavaFx expandable Textfield sample

被刻印的时光 ゝ 提交于 2019-12-20 06:14:55

问题


in my company we got a task to implement an autoexpandable textfield. As this functionality is not provided by default we had to develop it from scratch. There are many posibilities across web, how it can be achived, but no one worked for as, so we decided to put our code on SO, so other devs can also use it. As it is not possbile to expand a textfield the solution is textarea based:

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();
    }
  }
});
}
}

I hope it helps you :)


回答1:


that's work for me fine

 field.setMinWidth(40);

    field.textProperty().addListener(new ChangeListener<String>() {

     @Override
     public void changed(ObservableValue<? extends String> observable, String oldValue, 
      String newValue) {
         int len = newValue.length();
         field.setPrefWidth(len*10);
       if(newValue.isEmpty() || oldValue.isEmpty()){
            field.setPrefWidth(40);
        }        
     });



回答2:


you can set PrefWidth in the listener of the text field.

// add listner

'textField.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        textField.setPrefWidth(textField.getText().length());
    }
});'


来源:https://stackoverflow.com/questions/44141172/javafx-expandable-textfield-sample

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!