我正在制作一个程序,当我将鼠标悬停在连接它们的按钮上时,我需要将两个图像绘制成红色。问题是我需要在HOVERING时执行此操作,而不是在用户单击按钮时执行此操作。 我使用FXML和css进行样式化,但我没有看到任何方法从css的hover调用方法。
答案 0 :(得分:2)
在您的控制器中,您可以
private final PseudoClass highlightImage = PseudoClass.getPseudoClass("highlight");
@FXML
private Node someNode1 ;
@FXML
private Node someNode2 ;
@FXML
private Button button ;
public void initialize() {
button.hoverProperty().addListener((obs, wasHovered, isNowHovered) -> {
someNode1.pseudoClassStateChanged(highlightImage, isNowHovered);
someNode2.pseudoClassStateChanged(highlightImage, isNowHovered);
});
}
然后在CSS中你可以做
#someNode1, #someNode2 {
// regular styles
}
#someNode1:highlight, #someNode2:highlight {
// hover styles
}
这是一个SSCCE:
import javafx.css.PseudoClass;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.shape.Rectangle;
public class HighlightOnHoverController {
@FXML
private Rectangle leftRect ;
@FXML
private Rectangle rightRect ;
@FXML
private Button button ;
private final PseudoClass highlightRect = PseudoClass.getPseudoClass("highlight");
public void initialize() {
button.hoverProperty().addListener((obs, wasHovered, isNowHovered) -> {
leftRect.pseudoClassStateChanged(highlightRect, isNowHovered);
rightRect.pseudoClassStateChanged(highlightRect, isNowHovered);
});
}
@FXML
private void click() {
System.out.println("Button clicked");
}
}
HighlightOnHover.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.HBox?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.shape.Rectangle?>
<?import javafx.scene.control.Button?>
<HBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="HighlightOnHoverController" spacing="20" alignment="CENTER">
<padding>
<Insets top="10" left="10" right="10" bottom="10" />
</padding>
<Rectangle fx:id="leftRect" styleClass="rect" width="50" height="50" />
<Button fx:id="button" text="Click Me" onAction="#click" />
<Rectangle fx:id="rightRect" styleClass="rect" width="50" height="50" />
</HBox>
高亮上hover.css:
.rect {
-fx-fill: cornflowerblue ;
}
.rect:highlight {
-fx-fill: coral ;
}
HighlightOnHover.java:
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class HighlightOnHover extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("HighlightOnHover.fxml")));
scene.getStylesheets().add("highlight-on-hover.css");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
没有悬停在按钮上:
悬停在按钮上: