JavaFX:定义自定义控件 [英] JavaFX: Defining custom controls

查看:269
本文介绍了JavaFX:定义自定义控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you define your own custom control in JavaFX?

假设我有一个自定义控件,为了简单起见,让我们将其设为带有两个ButtonVBox,然后将整个内容称为CustomButton.

Say I have a custom control, for the sake of simplicity, let's just make it a VBox with two Button in it, and call the whole thing 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>

现在说我的根目录布局是这样的,我特别希望能够像Label或常规Button一样使用CustomButton.

Now say my root layout looks like this, I especially want to be able to use the CustomButton just as if it was a Label or a regular 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作为适当的控件,我必须更改什么?

What do I have to change in order to use my CustomButton as a proper control?

推荐答案

我认为这个问题已经在这里有了答案

I think this question has already an answer here CustomControl, for the answer, in order to use a custom component in your FXML you have to include it with the expression fx:include inside your container for exemple :

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

在这种情况下,可以以图形方式添加该组件,您可以使用他自己的控制器来处理它,这是指导老师

in this case the component is added graphically you can handle it with his own controller, here is the tutoriel fx:include

这篇关于JavaFX:定义自定义控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆