我有一个JavaFX
应用程序,我想在pane
的{{1}}事件中显示mousehover
,
我期望的输出类似于Windows任务栏预览样式,其中将鼠标悬停在 TaskBar 图标上时,预览窗格显示在顶部。 (如下所示)
如何使用JavaFX达到这种效果。
答案 0 :(得分:3)
代码是非常原始的,但是可以得到您所要求的核心功能(当然,可以根据需要以多种方式实现它,这取决于需求,我刚刚发布了对我来说实施最快的解决方案)>
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class StickyNotesApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
StackPane notedPane = new StackPane();
notedPane.setPrefSize(20, 20);
notedPane.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
notedPane.setStyle("-fx-background-color: purple;");
StackPane rootPane = new StackPane(notedPane);
rootPane.setPrefSize(400, 400);
StackPane.setAlignment(notedPane, Pos.BOTTOM_CENTER);
stage.setScene(new Scene(rootPane));
stage.show();
Stage stickyNotesStage = new Stage();
stickyNotesStage.initOwner(stage);
stickyNotesStage.initStyle(StageStyle.UNDECORATED);
StackPane stickyNotesPane = new StackPane();
stickyNotesPane.setPrefSize(200, 200);
stickyNotesPane.setStyle("-fx-background-color: yellow;");
stickyNotesStage.setScene(new Scene(stickyNotesPane));
notedPane.hoverProperty().addListener((ChangeListener<Boolean>) (observable, oldValue, newValue) -> {
if (newValue) {
stickyNotesStage.show();
} else {
stickyNotesStage.hide();
}
});
}
}
答案 1 :(得分:2)
正如@Przemek提到的,可以有很多方法来满足此要求。除了@Przemek实现之外,另一种方法是使用Popup控件。
下面是@Przemek的带有Popup实现的修改代码。
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Popup;
import javafx.stage.Stage;
public class StickyNotesApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
StackPane notedPane = new StackPane();
notedPane.setPrefSize(20, 20);
notedPane.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
notedPane.setStyle("-fx-background-color: purple;");
StackPane rootPane = new StackPane(notedPane);
rootPane.setPrefSize(400, 400);
StackPane.setAlignment(notedPane, Pos.BOTTOM_CENTER);
stage.setScene(new Scene(rootPane));
stage.show();
StackPane stickyNotesPane = new StackPane();
stickyNotesPane.setPrefSize(200, 200);
stickyNotesPane.setStyle("-fx-background-color: yellow;");
Popup popup = new Popup();
popup.getContent().add(stickyNotesPane);
notedPane.hoverProperty().addListener((obs, oldVal, newValue) -> {
if (newValue) {
Bounds bnds = notedPane.localToScreen(notedPane.getLayoutBounds());
double x = bnds.getMinX() - (stickyNotesPane.getWidth() / 2) + (notedPane.getWidth() / 2);
double y = bnds.getMinY() - stickyNotesPane.getHeight();
popup.show(notedPane, x, y);
} else {
popup.hide();
}
});
}
}