2016-12-01 187 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