Hyperlink in JEditorPane

前端 未结 1 1128
有刺的猬
有刺的猬 2020-11-29 10:06

I have few links displayed in JEditorPane ex:

http://www.google.com/finance?q=NYSE:C

http://www.google.com/finance?q=NASDAQ:MSFT

I want that I should

相关标签:
1条回答
  • 2020-11-29 10:47

    There's a few parts to this:

    Setup the JEditorPane correctly

    The JEditorPane needs to have the context type text/html, and it needs to be uneditable for links to be clickable:

    final JEditorPane editor = new JEditorPane();
    editor.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    editor.setEditable(false);
    

    Add the links

    You need to add actual <a> tags to the editor for them to be rendered as links:

    editor.setText("<a href=\"http://www.google.com/finance?q=NYSE:C\">C</a>, <a href=\"http://www.google.com/finance?q=NASDAQ:MSFT\">MSFT</a>");
    

    Add the link handler

    By default clicking the links won't do anything; you need a HyperlinkListener to deal with them:

    editor.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
               // Do something with e.getURL() here
            }
        }
    });
    

    How you launch the browser to handle e.getURL() is up to you. One way if you're using Java 6 and a supported platform is to use the Desktop class:

    if(Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(e.getURL().toURI());
    }
    
    0 讨论(0)
提交回复
热议问题