2 回答

TA貢獻1802條經驗 獲得超6個贊
我帶來的代碼提供了工具提示的正確定位,但遠非完美。帶來全面的解決方案需要大量工作(如果您愿意,我們可以討論)。我認為你有一個數學問題,并且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);
}
});
}
}

TA貢獻1818條經驗 獲得超8個贊
首先,您應該使用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 來自一個小實驗,我不確定為什么寬度和高度會偏離那個數量,但它似乎與工具提示中文本的長度或行數無關。
添加回答
舉報