[英]JavaFX How Can I Center a Tooltip on a Node?
我目前正在處理一種表單,該表單的功能是在將焦點從一個節點更改為另一個節點時進行驗證,並希望顯示一個包含錯誤的節點上方居中的工具提示。 我正在使用工具提示的show(Node ownerNode, double anchorX, double anchorY)
方法簽名來指定我要將其附加到哪個節點以及將其放置在何處。
我嘗試了以下代碼:
Tooltip tooltip = new Tooltip("Error");
tooltip.show(node, 0, 0);
double tooltipMiddle = tooltip.getWidth() / 2;
tooltip.hide();
double nodeMiddle = node.getWidth() / 2;
//Gets the node's x and y position within the window
Bounds bounds = node.localToScene(node.getBoundsInLocal());
//Tooltip's bottom-right corner is set to the anchor points, so I set x to
//the node's x coordinate plus half the width of the node plus half the width
//of the tooltip
tooltip.show(node,
bounds.getMinX() + nodeMiddle + tooltipMiddle, bounds.getMinY());
這使我離中心很近,但仍然不方便。 我一直在互聯網上尋求幫助,但是我什么也沒找到,所以我想在這里問。
我有什么機會了解為什么我無法按照自己的意願進行這項工作?
首先,您應該使用Bounds bounds = node.localToScreen(node.getBoundsInLocal());
因為可能不清楚相關Scene
是什么。
然后調用tooltip.show(node, bounds.getMinX(), bounds.getMinY());
應該會給您一個工具提示,其左上角與節點的左上角相同。
現在, tooltip.show(node, bounds.getMinX() + nodeMiddle - tooltipMiddle, bounds.getMinY() - tooltipHeight);
應該產生期望的結果,
double tooltipMiddle = (tooltip.getWidth()-18) / 2;
double tooltipHeight = tooltip.getHeight()-18;
double nodeMiddle = getWidth() / 2;
18來自一個小的實驗,我不確定為什么寬度和高度會偏離這個數量,但是它似乎與工具提示中文本的長度或行數無關。
我帶來的代碼提供了正確的工具提示位置,但還遠遠不夠完善。 帶來全面的解決方案將需要大量的工作(如果需要,我們可以進行討論)。 言歸正傳,我認為您遇到了數學問題, Tooltip類可能不是最佳選擇。
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class TooltipApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
TextField textField = new TextField();
textField.setPrefWidth(100.);
Button button = new Button("Tooltip");
HBox hBox = new HBox(textField, button);
hBox.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
Label label = new Label("Empty!");
label.setVisible(false);
Pane tooltipPane = new Pane(label);
tooltipPane.setMouseTransparent(true);
StackPane stackPane = new StackPane(hBox, tooltipPane);
stackPane.setPrefSize(600., 400.);
Scene scene = new Scene(stackPane);
stage.setScene(scene);
stage.show();
button.setOnMouseClicked(event -> {
if (label.isVisible()) {
label.setVisible(false);
} else {
Bounds sceneBounds = textField.localToScene(textField.getBoundsInLocal());
label.setLayoutX((sceneBounds.getMinX() + (sceneBounds.getWidth() / 2)) - (label.getWidth() / 2));
label.setLayoutY(sceneBounds.getMinY() - label.getHeight());
label.setVisible(true);
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.