如何在 JavaFX 中定义自己的自定义控件?
假设我有一个自定义控件,为了简单起见,让我们把它做成一个带有两个 Button
的 VBox
,然后将整个控件命名为 自定义按钮
。
自定义按钮.fxml
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox>
<Button text="Custom Button A"/>
<Button text="Custom Button B"/>
</VBox>
现在假设我的根布局看起来像这样,我特别希望能够像使用 Label
或常规 Button 一样使用
。CustomButton
MainView.fxml
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.Button?>
<HBox>
<Button text="Main Button"></Button>
<CustomButton />
</HBox>
主.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
用作正确的控件,我必须更改什么?
最佳答案
我想这个问题在这里已经有了答案CustomControl ,对于答案,为了在您的 FXML 中使用自定义组件,您必须将其与表达式 fx:include
一起包含在您的容器中,例如:
<fx:include source="CustomButton.fxml"/>
在这种情况下,组件是以图形方式添加的,您可以使用他自己的 Controller 来处理它,这里是教程 fx:include
关于JavaFX:定义自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911450/