将自定义组件添加到 intelliJ 中的 FXML 场景构建器

Add custom component to FXML scene builder in intelliJ

我想向 intelliJ 中的 javafx 场景生成器添加自定义组件/自定义组件。我目前正在使用 java 8.1。我听说可以使用 java 10 向场景构建器添加组件,因为它有 java 2.0。我安装了 java 10,但我不知道如何切换到 java 的那个版本。所以如果你知道如何解决这个问题,我很想听听。

提前致谢,

莱纳吉

编辑: 我明白为什么这个问题与其他帖子相似,因为直接问题是直接将自定义组件添加到场景构建器。不过这个问题是有存在的原因的,就是我用的是intelliJ的编辑器,那个编辑器是针对javafx 1.0左右的,添加自定义组件的功能是支持javafx 2.0,在java 10.现在真正的问题是:如何在intelliJ中更新场景生成器?我已经安装了 java 10,但我的项目仍在使用 java 8.1,我不知道如何更改它。我希望这可以解释为什么我的问题是相关的而不是重复的。感谢您阅读比最初问题更长的解释;p

I want to be able to make a java class, extending Pane or so, then assign children and actions to it, such as a slidebar with a textfield next to it, showing the value. I know that in the scene builder app, that is possible by importing a jar file with the class and dependencies straight into the scene builder, but I don't know how to do that in the scene builder in intelliJ.

使用方式没有区别Scene Builder。您只需在用户控件中添加属性(如果 属性 不是只读的,则使用 getter 和 setter)。在这种情况下,属性将出现在 Scene Builder 检查器中,您可以通过它们或直接编辑 FXML 文件来操作它们。

这里有一个例子(java8,但这无关紧要)

mycontrol.fxml

<fx:root type="javafx.scene.layout.HBox" xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml">
    <Label fx:id="label"/>
    <Slider fx:id="slider" HBox.hgrow="ALWAYS"/>
</fx:root>

public class MyControl extends HBox {

    @FXML
    private Label label;

    @FXML
    private Slider slider;

    private StringProperty labelName = new SimpleStringProperty();
    private DoubleProperty sliderPos = new SimpleDoubleProperty();

    public MyControl() {
        try {
            FXMLLoader l = new FXMLLoader(getClass().getResource("mycontrol.fxml"));
            l.setController(this);
            l.setRoot(this);
            l.load();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void initialize() {
        slider.setMin(0.0);
        slider.setMax(100.0);

        label.textProperty().bindBidirectional(labelName);
        slider.valueProperty().bindBidirectional(sliderPos);
    }

    public String getLabelName() {
        return labelName.get();
    }

    public StringProperty labelNameProperty() {
        return labelName;
    }

    public void setLabelName(String labelName) {
        this.labelName.set(labelName);
    }

    public double getSliderPos() {
        return sliderPos.get();
    }

    public DoubleProperty sliderPosProperty() {
        return sliderPos;
    }

    public void setSliderPos(double sliderPos) {
        this.sliderPos.set(sliderPos);
    }
}

这是这个用户控件使用的场景

sample.fxml

<AnchorPane xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.121" fx:controller="sample.Controller">
    <MyControl labelName="Test name" sliderPos="25.0" />
</AnchorPane>