簡體   English   中英

如何將可點擊的文本插入JTextPane?

[英]How to insert clickable text into a JTextPane?

我已經做了幾天的聊天程序,我完全不知道如何在不使用HTML的情況下創建美觀的可點擊文本。 我嘗試使用HTML,但結果異常奇怪(請參見下文)。 所以我現在只使用基本文本,而不是text / html。

帶有HTML的可點擊文本

我第一次嘗試添加可點擊的文本是使用JTextPane的能力,將Component與文本一起插入。 它可以插入並完美地工作,但是它在垂直方向上偏移並且看上去非常糟糕。 我試圖弄亂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 s(嘗試使用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只是為了證明鏈接可以正常工作,並演示了如何獲取鏈接字符串( getURL僅在鏈接為有效URL的情況下才有效)。
  • 無論是否帶有HyperlinkListener ,都無需設置光標。

原來我把setAlignmentY(0.85f); JTextPane而不是JLable。

如果您有一個偏移組件,則嘗試插入JTextPane中,請弄混它的Y對齊方式。 0.85f對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM