How to set button text in JavaFX?

送分小仙女□ 提交于 2019-12-02 13:11:38
Forager

Are you sure your elements are actually not null and that your assert statements are actually doing what they're supposed to? Click me for info on using assert statements. Make sure your variable declarations are left as @FXML private Button fx_btnHourUp; and that you never instantiate the button yourself via fx_btnHourUp = new Button();.

Are you using SceneBuilder 2.0 to create your fxmls? It's a program that allows you to design fxmls while avoiding many of these kinds of common errors. Download link here.

jewelsea

Why Button Text Does Not Change in Your Program

a. You never associate your controller with your FXML.

Because a controller is never associated with your FXML, a controller is never instantiated and your controller initialization code which sets the button text is never run.

b. You set a CSS id on your items in FXML rather than an FXML fx:id.

When you don't set an fx:id for items in FXML, FXML will not inject references to Java objects for those items into your controller class.

These are very common errors when first starting to write FXML applications. If you wanted, you could write to Oracle at javasedocs_us@oracle.com with a link to this answer and ask Oracle to add an FXML troubleshooting section or common issues section to their documentation.

Associating Controllers with FXML

EITHER:

  1. Use an fx:controller attribute.

    In your sample, add an fx:controller attribute to your root node; e.g.

    <BorderPane fx:controller="application.FX_TimerController" ...
    

    OR

  2. Set a controller in an FXML loader.

    Refer to Passing Parameters JavaFX FXML, for info on how to do this.

Setting fx:id Values

Instead of:

<Button ... id="fx_btnHourUp"/>

Write:

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