如何实现基于窗格的自定义JavaFX控件
问题描述:
我期待在JavaFX 8中实现基本的可扩展自定义控件,其中包含添加了其他控件的窗格。如何实现基于窗格的自定义JavaFX控件
因此,例如,它可以包含GridPane
,其持有TextField
,Button
和CheckBox
。
我不想子类Pane
或GridPane
,因为我不想将这些API公开给用户。所以,“一个由网格窗格组成的节点”与“一个扩展网格窗格的节点”相对。
我看到延伸Region
或Control
是可能的,这是推荐?将窗体大小和布局委派给窗格需要什么?
public class BasePaneControl extends Control {
private final Pane pane;
public BasePaneControl(Pane pane) {
this.pane = pane;
getChildren().add(pane);
}
// What do I need to delegate here to the pane to get sizing
// to affect and be calculated by the pane?
}
public class MyControl extends BasePaneControl {
private final GridPane gp = new GridPane();
public MyControl() {
super(gp);
gp.add(new TextField(), 0, 0);
gp.add(new CheckBox(), 0, 1);
gp.add(new Button("Whatever"), 0, 2);
}
// some methods to manage how the control works.
}
我需要帮忙实施BasePaneControl
以上请。
答
扩展区域,并覆盖layoutChildren方法。
您可以使用Region.snappedTopInset()方法(以及底部,左侧和右侧)来获取BasePaneControl的位置。然后根据可能是BasePaneControl的一部分的其他组件计算出您想要的窗格。
一旦您知道该窗格的位置,请致电resizeRelocate。
/**
* Invoked during the layout pass to layout this node and all its content.
*/
@Override protected void layoutChildren() {
// dimensions of this region
final double width = getWidth();
final double height = getHeight();
// coordinates for placing pane
double top = snappedTopInset();
double left = snappedLeftInset();
double bottom = snappedBottomInset();
double right = snappedRightInset();
// adjust dimensions for pane based on any nodes that are part of BasePaneControl
top += titleLabel.getHeight();
left += someOtherNode.getWidth();
// layout pane
pane.resizeRelocate(left,top,width-left-right,height-top-bottom);
}