How to set button text in JavaFX?

后端 未结 2 1681
旧时难觅i
旧时难觅i 2021-01-29 07:15

I\'m trying to set the button text using this code:

public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub
    /         


        
相关标签:
2条回答
  • 2021-01-29 07:51

    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"/>
    
    0 讨论(0)
  • 2021-01-29 07:52

    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.

    0 讨论(0)
提交回复
热议问题