gpt4 book ai didi

JavaFX 如何使工具提示在节点上居中?

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:02 24 4
gpt4 key购买 nike

我目前正在开发一种表单,该表单在将焦点从一个节点更改为另一个节点时进行验证,并希望在包含错误的节点上方居中显示工具提示(如果存在错误)。我使用工具提示的 show(NodeownerNode, doubleanchorX, doubleanchorY) 方法签名来指定我要将其附加到哪个节点以及将其放置在何处。

我尝试了以下代码:

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());

这已经让我非常接近中心了,但它仍然偏离。我一直在互联网上试图寻求帮助,但我只是没有找到任何帮助,所以我想我应该在这里询问。
我是否有机会深入了解为什么我无法按照我希望的方式进行此操作?

Validation message screenshot

最佳答案

我带来的代码提供了工具提示的正确定位,但远非完美。提供全面的解决方案需要大量的工作(如果您愿意,我们可以讨论)。追到底,我认为你有一个数学问题,而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);
}
});
}
}

关于JavaFX 如何使工具提示在节点上居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54142229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com