如何将可点击的文本插入到 JTextPane 中?

How to insert clickable text into a JTextPane?

几天来我一直在制作一个聊天程序,我完全不知道如何在不使用 HTML 的情况下创建一个漂亮的可点击文本。我尝试使用 HTML,但结果非常奇怪(见下文)。所以我现在只是在使用 基本文本而不是 text/html。

我第一次尝试添加可点击的文本是使用 JTextPane 的能力来插入 Components 和文本。它插入并工作得很好,但它垂直偏移并且看起来很糟糕。我试图弄乱 setAlignmentY,但没能将组件与文本对齐。

    JLabel l = new JLabel(test);
    l.setFont(this.getFont());
    l.setCursor(new Cursor(Cursor.HAND_CURSOR));
    l.setBackground(Color.RED); //Just so i could see it better for testing
    l.addMouseListener(new FakeMouseListener());
    this.insertComponent(l);  

我正在使用 JTextPane 并使用 doc.insertString 插入文本。我使用系统行分隔符跳过行,因此一行可以包含多个 doc.insertString(这是我 运行 在尝试使用 text/html 时遇到的麻烦)。

这会插入 HTML,没有任何对齐问题。我认为(“认为”是因为我没有足够的代码知道)当我使用 HTMLEditorKit.insertHTML.

时,由于 Document.insertString 你遇到了问题
public class Example extends JFrame {

    Example() {

        JEditorPane pane = new JEditorPane();
        pane.setEditable(false);
        pane.setContentType("text/html");
        HTMLDocument doc = (HTMLDocument) pane.getDocument();
        HTMLEditorKit editorKit = (HTMLEditorKit) pane.getEditorKit();

        try {
            editorKit.insertHTML(doc, doc.getLength(), "<a href=\"http://click.com\">clickable1</a>", 0, 0, null);
            editorKit.insertHTML(doc, doc.getLength(), "<a href=\"c2\">clickable2</a>", 0, 0, null);
            editorKit.insertHTML(doc, doc.getLength(), "<a href=\"c3\">clickable3</a>", 0, 0, null);
        } catch (BadLocationException | IOException e) {
            e.printStackTrace();
        }

        pane.addHyperlinkListener(new HyperlinkListener() {
            
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {

                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    System.out.println(e.getSourceElement());
                    if (e.getURL() != null)
                        System.out.println(e.getURL());
                    else
                        System.out.println(e.getDescription());
                    System.out.println("-----");
                }
            }
        });

        add(pane);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {

        new Example();
    }
}

备注:

    必须调用
  • setEditable(false) 才能使其正常工作(可能有一些复杂的方法可以使其正常工作)。
  • HyperlinkListener 只是为了证明 link 的工作原理,以及如何获取 link 字符串的一些演示(getURL 仅在以下情况下有效link 是有效的 URL).
  • 有无HyperlinkListener都不需要设置光标。

原来我为 JTextPane 而不是 JLable 设置了 setAlignmentY(0.85f);

如果您有一个试图插入到 JTextPane 中的偏移组件,请弄乱它的 Y 对齐方式。 0.85f 适合我。