How to implement tooltips in Java language?

Answered

I am currently working on an IDEA plugin. I aim to develop a plugin similar to GitHub Copilot. I already have access to a GPT interface, but I am unsure how to implement embedded tooltips. My programming language is Java. I found some resources suggesting the implementation of the InlayHintsProvider class. However, when I try to reference PsiMethod, it indicates that the package is missing. I am at a loss about what to do next. Can anyone assist me?

public class MyInlayHintsProvider implements InlayHintsProvider<MyInlayHintSettings> {


    private static final SettingsKey<MyInlayHintSettings> KEY = new SettingsKey<>("my.custom.hints");


    @NotNull
    @Override
    public SettingsKey<MyInlayHintSettings> getKey() {
        return KEY;
    }

    @Nls(capitalization = Nls.Capitalization.Sentence)
    @NotNull
    @Override
    public String getName() {
        return "My Custom Hints";
    }

    @Nullable
    @Override
    public String getPreviewText() {
        return "This is a preview text";
    }

    @NotNull
    @Override
    public ImmediateConfigurable createConfigurable(@NotNull MyInlayHintSettings myInlayHintSettings) {
        return new ImmediateConfigurable() {
            @NotNull
            @Override
            public JComponent createComponent(@NotNull ChangeListener changeListener) {
                JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                JLabel label = new JLabel("No configurable settings for this hint provider.");
                panel.add(label);
                return panel;
            }
        };
    }

    @NotNull
    @Override
    public MyInlayHintSettings createSettings() {
        return new MyInlayHintSettings();
    }

    @Nullable
    @Override
    public InlayHintsCollector getCollectorFor(@NotNull PsiFile psiFile, @NotNull Editor editor, @NotNull MyInlayHintSettings myInlayHintSettings, @NotNull InlayHintsSink inlayHintsSink) {
        return new FactoryInlayHintsCollector(editor) {
            @Override
            public boolean collect(@NotNull PsiElement psiElement, @NotNull Editor editor, @NotNull InlayHintsSink inlayHintsSink) {
                if (psiElement instanceof PsiMethod) {
                    PsiMethod method = (PsiMethod) psiElement;
                    PsiType returnType = method.getReturnType();

                    if (returnType != null) {
                        // 在方法的返回类型前添加一个内嵌提示
                        String text = "Return type: " + returnType.getPresentableText();
                        inlayHintsSink.addInlineElement(method.getTextOffset(), true, (InlayPresentation) new SimpleColoredText(text, null));
                    }
                }
                return true;
            }
        };
    }
}
 

0

Please sign in to leave a comment.