java JavaFX 8将图形添加到右侧的标题窗格中
我想在TitledPane
的标题中添加一个小图标。因此,我设置了一个空标题并添加一个HBox
,其中包含一个Label
和一个ImageView
作为图形。这样,图标将显示在靠近文本末尾的位置。我希望它总是显示在TitledPane
的右边框旁边。
我该怎么做?
我还尝试使用BorderPane
并将Label
添加到中心,将ImageView
添加到右侧,但是BorderPane
没有获得标题窗格的最大大小。
所以我尝试将MaxWidth设置为Max Value,但这没有帮助
有人知道怎么做吗
**编辑:**我创建的“自定义”控件将在stage中调用的方法中初始化。塞顿肖恩
public class CustomTitledPane extends TitledPane {
private Image alert;
private Image registered;
private Image deleted;
private ImageView img;
public CustomTitledPane(String titleText, Node node) {
super(titleText, node);
setAnimated(true);
setCollapsible(true);
img = new ImageView();
img.setFitHeight(10d);
img.setPreserveRatio(true);
img.setSmooth(true);
setGraphic(img);
setContentDisplay(ContentDisplay.RIGHT);
// apply css and force layout of nodes
applyCss();
layout();
// title region
Node titleRegion = lookup(".title");
// padding
Insets padding = ((StackPane) titleRegion).getPadding();
// image width
double graphicWidth = img.getLayoutBounds().getWidth();
// arrow
double arrowWidth = titleRegion.lookup(".arrow-button")
.getLayoutBounds().getWidth();
// text
double labelWidth = titleRegion.lookup(".text").getLayoutBounds()
.getWidth();
double nodesWidth = graphicWidth + padding.getLeft()
+ padding.getRight() + arrowWidth + labelWidth;
System.out.println("w: " + graphicWidth + " " + arrowWidth + " "
+ labelWidth);
graphicTextGapProperty().bind(widthProperty().subtract(nodesWidth));
try {
alert = new Image(new FileInputStream("img/Alert.png"));
registered = new Image(new FileInputStream("img/Registered.png"));
deleted = new Image(new FileInputStream("img/Deleted.png"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} }
下面是标题窗格的CSS:
.titled-pane {
-fx-text-fill: #006FD8;
}
.titled-pane > .title {
-fx-background-color: transparent;
-fx-border-color: linear-gradient(to right, white 0%, grey 30%, grey 70%, white 100%) transparent transparent transparent;
}
.titled-pane:expanded > .title {
-fx-border-color: grey transparent transparent transparent;
-fx-background-color: linear-gradient(to bottom, #DCE7F5, white);
}
.titled-pane:expanded > *.content {
-fx-border-width: 0;
}
# 1 楼答案
基于OP在其编辑的问题上显示的代码,此代码解决了一个事实,即在自定义类上显示阶段之前,在侦听器上创建了标题窗格
# 2 楼答案
无需将图形和文本包装在框中,因为您可以使用
setContentDisplay()
选择如何显示内容:一旦图像位于右侧,就需要设置图像和文本之间的间距。为此,我们可以使用一些查找来获得标题中节点的真实尺寸,一旦显示阶段
最后,我们将间隙空间绑定到标题的宽度属性减去这些维度
编辑
该示例现在支持在显示阶段之前创建
这就是它的样子: