我有一个界面
GraphicNodeProvider
:
public interface GraphicNodeProvider {
Node getNode(Graphic graphic);
}
Graphic
类型是一个枚举:
public enum Graphic {
HIDE,
SHOW,
REFRESH,
OPEN,
CREATE,
EDIT,
DELETE,
SAVE,
BACK,
...
}
Graphic
枚举表示 JavaFX 节点的图形,例如按钮,例如,Graphic.REFRESH
是刷新按钮的图形。
我将按如下方式实施
GraphicNodeProvider
:
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);
...
};
}
}
通过这种方式,我可以根据需要轻松更换应用程序图标节点,并将图形实现细节与我的控件分离。
在我的 JavaFX 控制器中,我通过构造函数注入
GraphicNodeProvider
:
public class AuthController {
@FXML
private Button loginButton;
@FXML
private Button signupButton;
private final GraphicNodeProvider graphicProvider;
public AuthController(GraphicNodeProvider graphicProvider) {
this.graphicProvider = graphicProvider;
}
}
目前,我正在使用注入的
initialize()
实例在控制器的GraphicNodeProvider
方法中设置所有按钮和其他节点的图形:
public class AuthController {
...
public void initialize() {
loginButton.setGraphic(graphicProvider.getNode(Graphic.LOGIN));
signupButton.setGraphic(graphicProvider.getNode(Graphic.SIGNUP));
...
}
但是,我想在 FXML 文件而不是控制器中设置图形。有没有办法访问
graphicProvider
中的注入字段AuthController
并从FXML文件中调用其getNode()
方法:
...
<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>
有没有办法通过调用
graphicProvider.getNode()
来设置上面 FXML 中按钮的图形?