在JavaFX中创建动态自定义控件

时间:2015-07-01 12:19:36

标签: model-view-controller javafx custom-controls

我的目标是代表

File View Grid

这是3列的set ns [new Simulator] set var 0 proc proc1{var}{ set $var 2 } proc proc2{var}{ puts stdout $var # I want $var to be 2, but it is 0. } $ns at 1 "proc1 $var" $ns at 5 "proc2 $var"

  • 第一个列包含一个GridPane,它是我刚刚打开的文件的名称
  • 第二列包含代表刷新率的Label
  • 第三列包含TextField和2 CheckBox

如果用户打开文件,我应该在此自定义控件中添加一行,如果没有文件打开,则Button为空。 我用这个开始我的代码:

控制类

GridPane

皮肤类

package view.component.fileView;

import javafx.scene.control.Control;
import javafx.scene.control.Skin;

public class FileViewGrid extends Control{

    @Override
    protected Skin<?> createDefaultSkin(){
        return new FileViewGridSkin(this);
    }
}

动态添加行的事实让我感到困惑。如果这是静态的,我会在我的皮肤类中添加我的所有元素,以及它们在控件类中的行为,但是现在这对我来说似乎不可能。

这是正确的方法吗?我应该使用FXML方法来创建一个客户控件吗?

1 个答案:

答案 0 :(得分:0)

This is a GridPane of 3 columns :

The first colum contains a Label that is the name of the file I just open
The second column contains a TextField to represent the refresh rate
The third colum contains a CheckBox and 2 Button

这表示ListView的单元格吗?

如果是的话,你有个好的开始。 秘诀是与PropertyBindings

一起玩

在你的控制中你必须将你想要暴露的内容放到外面。例如,Textfield有一个textProperty()。

在您的情况下,您可能希望公开您的ListView内的对象列表。

你的控制将是这样的:

package view.component.fileView;

import javafx.scene.control.Control;
import javafx.scene.control.Skin;

public class FileViewGrid extends Control{

ListProperty<YourBean> list = new SimpleListProperty(FXCollection.emptyObservableList())

    @Override
    protected Skin<?> createDefaultSkin(){
        return new FileViewGridSkin(this);
    }
}

和你的皮肤:

package view.component.fileView;

import javafx.scene.control.SkinBase;
import javafx.scene.layout.GridPane;

public class FileViewGridSkin extends SkinBase<FileViewGrid>{

FileViewGrid control;
Node root;
    protected FileViewGridSkin(FileViewGrid control) {
        super(control);
        this.control = control;
    }

        @Override
    public Node getNode() {
        if (root == null) {
            root = createRootNode();
        }
        return root;
    }

    public Node createRootNode(){
    //create your root node with something like: root = new Hbox() or whatever you want. Also you can load a FXML here.
      root = new Hbox();
     ListView<MyBean> listView = new ListView();
     listView.itemProperty().bind(control.list); //Here bind the listview items to your control list
    root.getChildrens().add(listView);
    }
}

并且当你在app上的某个地方使用你的控件时,终于完成了:

FileViewGrid fileViewGrid = new FileViewGrid();
fileViewGrid.list.add(elem); //Here the listview in your control should be refreshed automaticaly cause of bindings.

对于所有类型的组件,这都是一样的。

另外,您可以查看包含大量示例的source项目的ControlFX

相关问题