JTextPane中的可单击文本

Joe*_*Joe 7 java url swing jtextpane

我有一个声明如下的JTextPane:

JTextPane box = new JTextPane();
JScrollPane scroll = new JScrollPane();
StyledDocument doc = box.getStyledDocument();
scroll.setViewportView(box);
scroll = new JScrollPane(box);
Run Code Online (Sandbox Code Playgroud)

我正在附加文本如下:

public void appendChatText(String text)
{   
    try
    {
        doc.insertString(doc.getLength(), text, null);
        box.setAutoscrolls(true);
        box.setCaretPosition(box.getDocument().getLength());    
    }
    catch(BadLocationException e)
    {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

我还设法轻松地让JTextPane根据需要显示图像和组件,但我无法弄清楚如何将可点击文本编码到JTextPane中.例如,我希望它打印一条消息,上面写着"文件上传到服务器.接受*拒绝*",如果用户点击接受或拒绝字符串,则它会执行相应的功能.关于如何有效实现这一目标的任何想法?

Joe*_*Joe 7

我最终用MouseListener和一个扩展AsbstractAction的类来解决这个问题.我添加了我想要成为JTextPane的可点击链接的文本,如下所示:

`Style regularBlue = doc.addStyle("regularBlue", StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
 StyleConstants.setForeground(regularBlue, Color.BLUE);
 StyleConstants.setUnderline(regularBlue, true);
 regularBlue.addAttribute("linkact", new ChatLinkListener(textLink));
 doc.insertString(doc.getLength(), textLink, regularBlue);`
Run Code Online (Sandbox Code Playgroud)

我在其他地方的JTextPane上初始化了MouseListener,并将以下代码添加到我的侦听器类:

public void mouseClicked(MouseEvent e)
        {
            Element ele = doc.getCharacterElement(chatbox.viewToModel(e.getPoint()));
            AttributeSet as = ele.getAttributes();
            ChatLinkListener fla = (ChatLinkListener)as.getAttribute("linkact");
            if(fla != null)
            {
                fla.execute();
            }
        }
Run Code Online (Sandbox Code Playgroud)

最后,这引用了实际执行操作的类:

class ChatLinkListener extends AbstractAction
    {
        private String textLink;

        ChatLinkListener(String textLink)
        {
            this.textLink = textLink;
        }

        protected void execute()
        {
            if("accept".equals(url))
            {
                //execute code
            }
            else if("decline".equals(url))
            {
                //execute code
            }
        }

        public void actionPerformed(ActionEvent e)
        {
            execute();
        }
    }
Run Code Online (Sandbox Code Playgroud)