Is it possible to create programs in Java that create text to link in Chrome?

前端 未结 1 1240
盖世英雄少女心
盖世英雄少女心 2020-12-06 14:03

I apologize for the long question.

I was browsing a forum the other day and I saw a few pieces of text that were linking to youtube and other sites. I had to always

相关标签:
1条回答
  • 2020-12-06 14:40

    Use HTML in JEditorPane and add HyperLinkListener to detect click on URLs.

    Than use Desktop API to open default browser with the URL.

    Something like:

    enter image description here

    import java.awt.Desktop;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkListener;
    
    public class Test {
    
        public static void main(String[] argv) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
    
                    JEditorPane jep = new JEditorPane();
                    jep.setContentType("text/html");//set content as html
                    jep.setText("Welcome to <a href='http://stackoverflow.com/'>StackOverflow</a>.");
    
                    jep.setEditable(false);//so its not editable
                    jep.setOpaque(false);//so we dont see whit background
    
                    jep.addHyperlinkListener(new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent hle) {
                            if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
                                System.out.println(hle.getURL());
                                Desktop desktop = Desktop.getDesktop();
                                try {
                                    desktop.browse(hle.getURL().toURI());
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }
                    });
    
    
                    JFrame f = new JFrame("HyperlinkListener");
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.add(jep);
                    f.pack();
                    f.setVisible(true);
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题