我正在使用Java 8。我在工具栏上有按钮。
我想要实现以下内容:
我想要实现以下内容:
- 在工具栏的普通状态下(未悬停鼠标),只能看到按钮标签(没有背景,也没有边框)。
- 当用户将鼠标悬停在按钮上时,应该看到普通的按钮。
使用样式来移除背景:
.button {
-fx-background-color: transparent;
}
当鼠标悬停时,只需使用modena.css
中的按钮样式即可恢复所有内容:
.button:hover{
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-background-insets: 0 0 -1 0, 0, 1, 2;
-fx-background-radius: 3px, 3px, 2px, 1px;
-fx-padding: 0.333333em 0.666667em 0.333333em 0.666667em; /* 4 8 4 8 */
-fx-text-fill: -fx-text-base-color;
-fx-alignment: CENTER;
-fx-content-display: LEFT;
}
我同意netzwerg的观点。如果你正在使用JavaFX中的FXML,则应在控制器类的initialize()方法中包含以下代码行。
控制器类示例:
public class Controller implements Initializable{
private Button test;
private static final String IDLE_BUTTON_STYLE = "-fx-background-color: transparent;";
private static final String HOVERED_BUTTON_STYLE = "-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;";
@Override
public void initialize(URL location, ResourceBundle resources) {
button.setStyle(IDLE_BUTTON_STYLE);
button.setOnMouseEntered(e -> button.setStyle(HOVERED_BUTTON_STYLE));
button.setOnMouseExited(e -> button.setStyle(IDLE_BUTTON_STYLE));
}
}
通过鼠标监听器可以控制背景透明度,即通过编程设置CSS(这样就无需外部样式表):
final String IDLE_BUTTON_STYLE = "-fx-background-color: transparent;";
final String HOVERED_BUTTON_STYLE = "-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;";
button.setStyle(IDLE_BUTTON_STYLE);
button.setOnMouseEntered(e -> button.setStyle(HOVERED_BUTTON_STYLE));
button.setOnMouseExited(e -> button.setStyle(IDLE_BUTTON_STYLE));