如何在Fxml上添加costum组件?

时间:2018-02-16 02:10:06

标签: javafx fxml

我有一个costum按钮,但是如何在fxml文件中使用它? 我试图创建一个普通的Button,并在控制器上执行类似“@FXML”的操作     私有CrazyButton按钮;“这会导致应用程序崩溃。

那么让我们看一下CrazyButton的例子,如何在fxml文件中添加costumComponent?

import javafx.scene.control.Button;

public class CrazyButton extends Button {

    public CrazyButton(){
        setText("Crazy");
    }
}

这是我的fxml文件:

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
      fx:controller="sample.Controller" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1">
   <children>
       <!--I Wanted my costum button to be here-->
   </children>
</Pane>

所以我可以在我自己的控制器上使用它:

public class Controller {

    @FXML
    private CrazyButton button;

    @FXML
    private void initialize() {

    }
}

1 个答案:

答案 0 :(得分:1)

JavaFX库类没有&#34;特权&#34;在任何意义上都与FXML有关; FXMLLoader以相同的方式实例化所有类。你只需要确保你的自定义类在一个包中(使用&#34;默认包&#34;这是非常糟糕的做法),然后在FXML中导入它并使用它与你做的完全相同任何其他类。如果您的课程在my.package个包中,则会显示

<?import javafx.scene.layout.Pane ?>
<?import my.package.CrazyButton ?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
      fx:controller="sample.Controller" xmlns="http://javafx.com/javafx/8.0.112" xmlns:fx="http://javafx.com/fxml/1">
   <children>
       <CrazyButton fx:id="button" />
   </children>
</Pane>