0

enter image description here

following problem: I have got a textfield, where the user can input a name for instance. After hitting the enter key, the textfield hides and a label including that text shows. The problem: I need immediately after doing this the new widthProperty of the label, but it always returns 0. Im guessing, the node just has not been drawn yet. Is there any possibility to force a node to get drawn or any other solution for that? Thanks a lot!

String userInput = textField.getText();
textField.setManaged(false);
textField.setVisible(false);
label.setManaged(true);
label.setVisible(true);
label.setText(userInput);

double newWidth = label.widthProperty().doubleValue();      //This is 0!
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
decman
  • 49
  • 6
  • You can (but probably shouldn't) call `layout()` on the parent of the `label`. Why do you think you need the width of the label? – James_D May 21 '18 at 12:58
  • The label is the name of the link of two nodes. The label lays in an AnchorPane, which needs to be centerized between the two nodes all the time. Therefore, i need half the width of the current label. – decman May 21 '18 at 13:00
  • 2
    Use a layout pane that manages that for you, instead of trying to do it yourself. In the unlikely event that no existing layout pane (or combination of them) gives you what you need, you should subclass `Pane` and override `layoutChildren()` to implement your own layout code. An `AnchorPane` is pretty much useless for managing layouts where the positions of components depend on each other. – James_D May 21 '18 at 13:02
  • Why would you not recommend using layout()? I am pretty new to JavaFX and cannot think of other panes which could do the job for me, since the width of the label can change all the time. – decman May 21 '18 at 13:07
  • Because you force an entire additional layout pass: you layout the parent once to force it to determine the label's size, then (presumably) reposition the label, so another layout pass is needed. The proper place to perform any kind of layout computation is in the `layoutChildren()` method - either in an implementation provided in an existing class (preferable), or in highly specialized cases in an implementation you write. – James_D May 21 '18 at 13:09
  • Any time the width of the label changes, the parent will be notified and it will recalculate its layout the next time the scene is rendered. – James_D May 21 '18 at 13:10
  • 2
    E.g. you could put your nodes and the label in a `HBox`, set the label's alignment to `CENTER`, its max width to `Double.MAX_VALUE`, and use `HBox.setHGrow(label, Priority.ALWAYS)`. – James_D May 21 '18 at 13:13
  • Thanks for your help James_D! I will try to implement your advices! – decman May 21 '18 at 13:16

0 Answers0