I have an interface GraphicNodeProvider
:
public interface GraphicNodeProvider {
Node getNode(Graphic graphic);
}
The Graphic
type is an enum:
public enum Graphic {
HIDE,
SHOW,
REFRESH,
OPEN,
CREATE,
EDIT,
DELETE,
SAVE,
BACK,
...
}
The Graphic
enum represents the graphic for a JavaFX node like a button, for example, Graphic.REFRESH
is the graphic for a refresh button.
I'll implement GraphicNodeProvider
as follows:
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;
...
public class DefaultGraphicNodeProvider implements GraphicNodeProvider {
public static final String FONT_FAMILY = "FontAwesome";
@Override
public Node getNode(Graphic graphic) {
return switch (graphic) {
case REFRESH -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.REFRESH);
case SHOW -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.EYE);
case HIDE -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.EYE_SLASH);
case OPEN -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.FOLDER_OPEN);
case CREATE -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.PLUS);
case EDIT -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.PENCIL);
case DELETE -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.TRASH);
case SAVE -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.SAVE);
case BACK -> new Glyph(FONT_FAMILY, FontAwesome.Glyph.ARROW_LEFT);
...
};
}
}
This way I can easily swap out the app icon nodes if required and decouple graphic implementation details from my controls.
In my JavaFX controller, I'm injecting GraphicNodeProvider
via the constructor:
public class AuthController {
@FXML
private Button loginButton;
@FXML
private Button signupButton;
private final GraphicNodeProvider graphicProvider;
public AuthController(GraphicNodeProvider graphicProvider) {
this.graphicProvider = graphicProvider;
}
}
Currently, I'm setting the graphics of all the buttons and other nodes in the controller's initialize()
method using the injected GraphicNodeProvider
instance:
public class AuthController {
...
public void initialize() {
loginButton.setGraphic(graphicProvider.getNode(Graphic.LOGIN));
signupButton.setGraphic(graphicProvider.getNode(Graphic.SIGNUP));
...
}
However, I would like to set the graphic in the FXML file instead of the controller. Is there a way to access the injected field graphicProvider
in AuthController
and call its getNode()
method from the FXML file using FXML syntax:
...
<HBox alignment="CENTER">
<Button fx:id="loginButton" graphic="#graphicProvider.getNode(Graphic.LOGIN)" text="%auth.login.button.login"/>
<Button fx:id="signUpButton" graphic="#graphicProvider.getNode(Graphic.SIGNUP)" text="%auth.signup.button.signup"/>
</HBox>
Is there a way I can set the graphic of the buttons in the FXML above by calling graphicProvider.getNode()
?
Project Link for Reference: https://github.com/amal-stack/notebooksfx