2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
我?guī)淼拇a提供了工具提示的正確定位,但遠(yuǎn)非完美。帶來全面的解決方案需要大量工作(如果您愿意,我們可以討論)。我認(rèn)為你有一個(gè)數(shù)學(xué)問題,并且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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
首先,您應(yīng)該使用Bounds bounds = node.localToScreen(node.getBoundsInLocal());,因?yàn)榭赡懿磺宄嚓P(guān)Scene內(nèi)容是什么。
然后調(diào)用tooltip.show(node, bounds.getMinX(), bounds.getMinY());應(yīng)該給你一個(gè)工具提示,其左上角與節(jié)點(diǎn)的左上角相同。
現(xiàn)在,tooltip.show(node, bounds.getMinX() + nodeMiddle - tooltipMiddle, bounds.getMinY() - tooltipHeight);應(yīng)該產(chǎn)生所需的結(jié)果,它確實(shí)適用于
double tooltipMiddle = (tooltip.getWidth()-18) / 2;
double tooltipHeight = tooltip.getHeight()-18;
double nodeMiddle = getWidth() / 2;
18 來自一個(gè)小實(shí)驗(yàn),我不確定為什么寬度和高度會(huì)偏離那個(gè)數(shù)量,但它似乎與工具提示中文本的長度或行數(shù)無關(guān)。
添加回答
舉報(bào)