繁体   English   中英

JavaFx HBox 删除间距

[英]JavaFx HBox remove spacing

到目前为止我所拥有的

我试图用 javaFx 实现一个多行 TextInput,一个能够显示表情符号的文本输入,我使用了 FlowPanes 的 VBox(每行一个 FlowPane),用空格将行分割成单词,单词显示在 HBox 中并且 HBox 将包含用于文本的 Text 节点和用于 Emojis 的 ImageView,当前设置如下图所示

插图

以下屏幕截图显示了我到目前为止的内容

在此处输入图片说明


问题

我面临的问题是复杂的词,当多个表情符号 (ImageViews) 显示在 HBox 中时,每个图像的 Carret 位置估计都会出错半个像素(因为我假设 HBox 的宽度会等于其子项的 fitWidths 的总和?,但不是),就好像 HBox 具有某种间距,尽管间距属性设置为 0。

如果很多表情符号一起显示效果会更糟,如下面的截图所示

在此处输入图片说明 在此处输入图片说明

它也不是填充或边框,任何帮助将不胜感激,我很抱歉冗长乏味的解释,我不得不添加它以防它帮助任何人帮助我解决问题。

经过大量调查,结果证明是我将子 ImageViews 的 fitWidth 设置为十进制值(非整数)引起的,ImageView 接受 double 作为 fitWidth 但它似乎四舍五入为最接近的更大整数时渲染,调用 getFitWidth() 方法仍会返回您设置的双精度值,但父级会使用舍入值布置它们(因为我猜物理像素不能显示半个像素,对吗?)。

因此,当 ImageViews 的 fitWidths 为非整数时,在 HBox 父级上调用 getWidth() 将返回比子 ImageViews 的 fitWidths 总和更大的值。

这可以使用以下代码进行测试

ArrayList<Image> images = new ArrayList<Image>();

//Fill the list with N images

StackPane root = new StackPane();
root.setPadding(new Insets(15));

HBox parent = new HBox(0);
for (Image image : images) {
    ImageView view = new ImageView(image);
    view.setPreserveRatio(true);
    view.setFitWidth(fitWidth);
    parent.getChildren().add(view);
}

root.getChildren().add(parent);

ps.setOnShown(event -> {
    double sum = 0;
    for (Node node : parent.getChildren()) {
        sum += ((ImageView) node).getFitWidth();
    }
    System.out.println("fitWidth : " + fitWidth);
    System.out.println("Sum of fitWidths of child ImageViews : " + sum);
    System.out.println("Width of the parent HBox : " + parent.getWidth());
});

ps.setScene(new Scene(root));
ps.show();

以 31.5 和 32.0 的 fitWidth 运行它会得到以下结果

fitWidth : 31.5
Sum of fitWidths of child ImageViews : 315.0
Width of the parent HBox : 320.0

fitWidth : 32.0
Sum of fitWidths of child ImageViews : 320.0
Width of the parent HBox : 320.0

请注意,父级的宽度相同但 fitWidths 的总和不同,因为该值在布局或渲染期间的某个点被四舍五入,这导致了问题中描述的问题。

解决这个问题会因上下文而异,我通过在设置 fitWidth 时将 double 转换为 int 来解决它,但这实际上取决于开发人员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM