如何在JTextArea中添加可点击的URL?

时间:2011-05-14 09:43:15

标签: java swing url jtextarea

我正在编写一个应用程序,我正在使用JTextArea来显示一些文本。现在我想在文本区域中显示一些可点击的URL以及普通文本,如果用户点击该URL,我想要在新的Web浏览器窗口中打开所引用的URL的网页。

3 个答案:

答案 0 :(得分:3)

将JEditorPane与HTMLEditorKit或JTextPane一起使用,并将内容类型设置为“text / html”

答案 1 :(得分:2)

  

.. url引用应该在新的Web浏览器窗口中打开。

// 1.6+
Desktop.getDesktop().browse(URI);

答案 2 :(得分:0)

以下是从JTextArea打开链接的示例:

                JTextArea jtxa = new JTextArea(25,100);
                JScrollPane jsp = new JScrollPane(jtxa);
                JPanel jp = new JPanel();
                jp.add(jsp);
                jp.setSize(100,50);

                jtxa.addMouseListener(new MouseAdapter()
                {
                    public void mouseClicked(MouseEvent me)
                    {
                        if(me.getClickCount()==2) //making sure there was a double click
                        {
                            int x = me.getX();
                            int y = me.getY();

                            int startOffset = jtxa.viewToModel(new Point(x, y));//where on jtextarea click was made
                            String text = jtxa.getText();
                            int searchHttp = 0;
                            int wordEndIndex = 0;
                            String[] words = text.split("\\s");//spliting the text to words. link will be a single word

                            for(String word:words)
                            {
                                if(word.startsWith("https://") || word.startsWith("http://"))//looking for the word representing the link
                                {
                                    searchHttp = text.indexOf(word);
                                    wordEndIndex = searchHttp+word.length();
                                    if(startOffset>=searchHttp && startOffset<=wordEndIndex)//after the link word was found, making sure the double click was made on this link
                                    {
                                        try
                                        {
                                            jtxa.select(searchHttp, wordEndIndex);
                                            desk.browse(new URI(word)); //opening the link in browser. Desktop desk = Desktop.getDesktop();
                                        }
                                        catch(Exception e)
                                        {
                                            e.printStackTrace();
                                        }

                                    }
                                }
                            }                           
                        }

                    }
                });