2016-12-01 188 views
2

如何在JavaFX中定义自己的自定义控件?JavaFX:定义自定义控件

假设我有一个自定义控件,为了简单起见,我们只需将其设为VBox,其中包含两个Button,然后调用CustomButton

CustomButton.fxml

<?import javafx.scene.control.Button?> 
<?import javafx.scene.layout.VBox?> 
<VBox> 
    <Button text="Custom Button A"/> 
    <Button text="Custom Button B"/> 
</VBox> 

现在说我的根布局看起来像这样,我特别希望能够使用CustomButton就好像它是一个Label或常规Button

MainView.fxml

<?import javafx.scene.layout.HBox?> 
<?import javafx.scene.control.Button?> 
<HBox> 
    <Button text="Main Button"></Button> 
    <CustomButton /> 
</HBox> 

Main.java

import javafx.application.Application; 
import javafx.fxml.FXMLLoader; 
import javafx.scene.Parent; 
import javafx.scene.Scene; 
import javafx.stage.Stage; 

public class Main extends Application { 

    @Override 
    public void start(Stage primaryStage) throws Exception{ 
     Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml")); 
     primaryStage.setScene(new Scene(root)); 
     primaryStage.show(); 
    } 


    public static void main(String[] args) { 
     launch(args); 
    } 
} 

目前,这导致

Exception in thread "main" java.lang.RuntimeException: Exception in Application start method 
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917) 
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: javafx.fxml.LoadException: CustomButton is not a valid type. 

我有什么才能使用改变我的CustomButton作为一个适当的控制?

+1

的可能的复制[如何使用FXML创建JavaFX中2.0自定义组件?](HTTP://计算器.COM /问题S/8434787 /如何到创建定制的组件功能于JavaFX的2-0-使用-FXML) –

回答

0

我认为这个问题已经在这里回答CustomControl,答案,为了使用自定义组件在FXML你有表达fx:include您的容器内进行为例,包括它:

<fx:include source="CustomButton.fxml"/> 

在这种情况下,组件添加图形,你可以用自己的控制器处理它,这里是tutoriel fx:include