Search code examples
javafxjavafx-8fxml

JavaFX: Binding expression in FXML document


In JavaFX 8 is it still possible to bind a control property directly in FXML to a property of the controller? Something like:

<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<GridPane xmlns:fx="http://javafx.com/fxml"
   fx:controller="application.PaneController" minWidth="200">
   <Label id="counterLabel" text="${controller.counter}" />
   <Button translateX="50" text="Subtract 1"
      onAction="#handleStartButtonAction" />
</GridPane>

The above seems not to work.


Solution

  • Yes this is possible assuming you implement the correct methods in the controller:

    public class PaneController {
    
        private final IntegerProperty counter = new SimpleIntegerProperty(100);
    
        public IntegerProperty counterProperty() {
            return counter;
        }
    
        // this is also required
        public int getCounter() {
            return counter.get();
        }
    
        public void handleStartButtonAction() {
            counter.set(counter.get() - 1);
        }
    
    }
    

    Also I'm not sure if placing both Nodes in the same cell is the best decision...