带有工具提示和超链接的 JavaFX "quickfixes"



JavaFX是否提供类似Eclipse Quickfixes的功能?这意味着你将鼠标悬停在一个坏掉的东西上,并为它找到一些可以立即应用的解决方案。我知道有工具提示,但它们只能包含文本,我需要一些可点击的东西。另一个解决方案是类似Dialogs,但我不想打开另一个窗口。我希望它出现在当前的舞台上。有什么建议吗?

编辑:为了明确起见,我想在基于JavaFX的应用程序中采用eclipse快速修复的概念,也许在悬停在圆形实例上时会显示"快速修复"。我不想检查任何(java/javafx)源代码。

第2版:我现在在工具提示上有一个超链接:

HBox box = new HBox();
Tooltip tooltip = new Tooltip();
tooltip.setText("Select an option:");
tooltip.setGraphic(new Hyperlink("Option 1"));
Tooltip.install(box, tooltip);

我现在有三个新问题:

  1. 如何使工具提示在离开HBox时不消失,并在将鼠标输入工具提示时保持不变
  2. 如何添加多个图形/超链接?这可能吗
  3. 如何首先显示文本,然后在新行中显示图形

提前感谢!

您可以使用setGraphic()方法将任何节点添加到工具提示中。下面是一个简单的例子,演示使用工具提示进行"快速修复"功能:

import java.util.Random;
import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TooltipWithQuickfix extends Application {
@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), true);
textField.setTextFormatter(new TextFormatter<Integer>(c -> {
if (c.getText().matches("\d*")) {
return c ;
}
return null ;
}));
textField.textProperty().isEmpty().addListener((obs, wasEmpty, isNowEmpty) ->
textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), isNowEmpty));
Tooltip quickFix = new Tooltip();
Hyperlink setToDefault = new Hyperlink("Set to default");
Hyperlink setToRandom = new Hyperlink("Set to random");
setToDefault.setOnAction(e -> {
textField.setText("42");
quickFix.hide();
});
Random rng = new Random();
setToRandom.setOnAction(e -> {
textField.setText(Integer.toString(rng.nextInt(100)));
quickFix.hide();
});
VBox quickFixContent = new VBox(new Label("Field cannot be empty"), setToDefault, setToRandom);
quickFixContent.setOnMouseExited(e -> quickFix.hide());
quickFix.setGraphic(quickFixContent);
textField.setOnMouseEntered(e -> {
if (textField.getText().isEmpty()) {
quickFix.show(textField, e.getScreenX(), e.getScreenY());
}
});

VBox root = new VBox(textField);
root.getStylesheets().add("style.css");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

使用样式表(style.css):

.root {
-fx-alignment: center ;
-fx-padding: 24 10 ;
}
.text-field:invalid {
-fx-control-inner-background: #ff7979 ;
-fx-focus-color: red ;
}

最新更新