首页 > 解决方案 > JavaFX按钮背景向右溢出1px

问题描述

当我将新设置Background为 aButton时,Background右侧多了 1px,颜色的不透明度 <1。

有没有办法删除 1px 或填充它(不透明度 1)?1px 并不多,但是如果你把它们放在一起,那 1px 就会变成一个可见的空白区域。当按钮添加到Paneor时,我看到了问题Group,当使用HBoxor时VBox,1px 被填充。不幸的是,我需要使用Paneor Group。我尝试使用自定义插图,但问题仍然存在。

代码示例:

Background background = new Background(new BackgroundFill(Color.GREEN, CornerRadii.EMPTY, Insets.EMPTY));
Font font = new Font("Times New Roman", 16);

Button a = new Button("A");
a.setFont(font);
a.setBackground(background);
a.setLayoutX(10);
a.setLayoutY(10);
pane.getChildren().add(a);

Button aa = new Button("AA");
aa.setFont(font);
aa.setBackground(background);
aa.setLayoutX(10);
aa.setLayoutY(45);
pane.getChildren().add(aa);

Button aaa = new Button("AAA");
aaa.setFont(font);
aaa.setBackground(background);
aaa.setLayoutX(10);
aaa.setLayoutY(80);
pane.getChildren().add(aaa);

结果(图像被放大,以便更好地看到 1px):

1px 的样子(红线上方的 1px):

1px 的样子

1px 的样子

它看起来如何彼此相邻(您可以看到空间不是白色,也不是绿色,而是浅绿色:

彼此相邻的样子

彼此相邻的样子

标签: javafx

解决方案


观察到的效果是按钮宽度不是整数的结果。这导致那些没有完全覆盖像素的部分被渲染为半透明。

Pane不幸的是,没有考虑该snapToPixel属性,只是将子项的大小调整为根据其属性计算的大小。

要解决这个问题,请使用一种Pane将坐标捕捉到像素的类型,例如,VBox或者在这种情况下,AnchorPane没有设置任何锚点。

Pane pane = new AnchorPane();

推荐阅读