java - How can I get the width and the height of a JavaFX Label? -


there 2 methods getwidth , getheight return old label size if changed label text value.

for example, in code, background not correctly resized:

label speedlabel = new label(); rectangle backgroundlabel = new rectangle();  // initialization  // change label text speedlabel.settext(connection.getspeed_bps()); // sets bigger number  // adjust background backgroundlabel.setwidth(speedlabel.getwidth()); backgroundlabel.setheight(speedlabel.getheight()); 

after initialization, label that:

enter image description here

and after text change , background adjustment, label that:

enter image description here

i had @ post recommends deprecated method:

how label.getwidth() in javafx

the reason returning "old" size label doesn't updated on gui in moment when set textproperty of it, therefore size not changed.

you can listen widthproperty , heightproperty of label , resize rectangle in listener:

speedlabel.widthproperty().addlistener((obs, oldval, newval) -> {     backgroundlabel.setwidth(newval.doublevalue()); });  speedlabel.heightproperty().addlistener((obs, oldval, newval) -> {     backgroundlabel.setheight(newval.doublevalue()); }); 

or use bindings between properties:

backgroundlabel.heightproperty().bind(speedlabel.heightproperty()); backgroundlabel.widthproperty().bind(speedlabel.widthproperty()); 

but if want achieve label background, don't need rectangle, css - can check question: fxml stackpane doesn't align children correctly


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -