JavaFX - 在Button上留下边框而不移动文本或调整其大小

时间:2016-07-23 20:34:01

标签: java css button javafx

我想创建一个Button。一开始它没有边框,只有背景颜色。所以我设置了以下CSS属性:

.button, .toggle-button {
  -fx-background-color: #373e48;
  -fx-background-radius: 0;
}

当按下/选择Button时,左侧会出现一个边框,所以我添加了这个:

.button:pressed, .toggle-button:selected {
  -fx-border-color: #ee543a;
  -fx-border-width: 0 0 0 2px;
}

问题在于,每次显示边框时,Button都会变得更宽。

我还尝试将对齐设置为center-right并添加最小宽度,但如果Button变大,它就不再那样了。它确实看起来不像我想要的那样。

那么,如果没有这种行为,我怎么能这样做呢?优选地,文本与中心对齐。

1 个答案:

答案 0 :(得分:3)

您可以使用-fx-background-insets属性

在CSS中执行此操作
.button, .toggle-button {
  -fx-background-color: #373e48;
  -fx-background-radius: 0;
  -fx-text-fill: white;
}

.button:pressed, .toggle-button:selected {
  -fx-background-color: #ee543a, #373e48;
  -fx-background-insets: 0, 0 0 0 2;
}

enter image description here

第二个选择器创建两种颜色的两个层。原始背景颜色在左侧获得2像素插入,因此底层(“边框”的颜色)将在左侧显示为2像素边框。

仔细查看此选择器:-fx-background-insets: 0, 0 0 0 2;第一个(基础)背景颜色没有插入。顶部的颜色左侧有2个像素插图,因为四个数字表示top, right, bottom, left

注意:文本对齐是不必要的,因为ButtonToggleButton的默认文本对齐方式是居中的,但无论如何您也可以对齐文本CSS:

.button, .toggle-button {
    -fx-text-alignment: center; //* or left, right, justify  *//
}