也许有人知道答案并试着帮助我。
我正在创建自己的按钮。
<fx:root maxHeight="100.0" maxWidth="100.0" minHeight="50.0" minWidth="50.0" prefHeight="80.0" prefWidth="80.0" style="-fx-background-color: red;" type="StackPane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" >
<children>
<ImageView fx:id="baseImage" fitHeight="66.0" fitWidth="72.0" pickOnBounds="true" preserveRatio="true" StackPane.alignment="TOP_CENTER" />
<Label fx:id="textBtn" alignment="BOTTOM_LEFT" prefHeight="17.0" prefWidth="75.0" textFill="WHITE" textOverrun="CLIP" StackPane.alignment="BOTTOM_LEFT" />
</children>
</fx:root>
所以当我在FXML文件中创建它时,我需要更改我的按钮(图像和标签)。
<MyButton layoutX="200.0" layoutY="162.0" />
e.g
<MyButton layoutX="200.0" layoutY="162.0" image="" text="" />
有人能帮助我吗?
我的Java代码
public class MyButton extends StackPane
{
@FXML
private ImageView baseImage;
@FXML
private Label textBtn;
public MyButton()
{
FXMLLoader fxmlLoader =new FXMLLoader(getClass().getResource("/pl/edu/wat/wcy/pz/icons/MyButtonView.fxml"));
fxmlLoader.setController(this);
fxmlLoader.setRoot(this);
init();
try {
fxmlLoader.load();
}
catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public Label getTextBtn() {
return textBtn;
}
public void setTextBtn(Label textBtn) {
this.textBtn = textBtn;
}
public ImageView getBaseImage() {
return baseImage;
}
public void setBaseImage(Image location) {
this.baseImage.setImage(location);
}
public void setButton(Label textBtn, Image location){
this.baseImage.setImage(location);
this.textBtn = textBtn;
}
但我关心的图标是在FXML文件中更改的,而不是JavaCode
}
答案 0 :(得分:0)
如果要在FXML中设置属性:
<MyButton layoutX="200.0" layoutY="162.0" image="" text="" />
您必须在相应的类中定义这些属性。特别是,MyButton
必须定义setImage(...)
和setText(...)
方法(它已经从setLayoutX(...)
继承了setLayoutY(...)
和StackPane
。很难确切地知道您想要的功能,但您可能希望将它们设置为JavaFX属性。如果打算将这些映射到FXML文件中定义的Label
和ImageView
,则只需从控件中公开相关属性即可。您可能需要稍微努力将字符串从image属性映射到正确的内容。
public class MyButton extends StackPane
{
@FXML
private ImageView baseImage;
@FXML
private Label textBtn;
public MyButton()
{
FXMLLoader fxmlLoader =new FXMLLoader(getClass().getResource("/pl/edu/wat/wcy/pz/icons/MyButtonView.fxml"));
fxmlLoader.setController(this);
fxmlLoader.setRoot(this);
// not sure what this is:
// init();
// note that if you define
// public void initialize() {...}
// it will be called
// automatically during the FXMLLoader.load() method
try {
fxmlLoader.load();
}
catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public StringPropergty textProperty() {
return textBtn.textProperty();
}
public final String getText() {
return textProperty().get();
}
public final void setText(String text) {
textProperty().set(text);
}
// similarly expose a property for image, but you need to be able to coerce it from a String
}
(顺便提一下,我认为这仅仅是为了理解如何做到这一点的一个例子。示例中的所有内容都可以使用常规按钮完成。只是想让其他人阅读这篇文章。 )