I am writing an application and in that I am using JTextArea
to display some text. Now I want to show some clickable URL in text area along with the normal text and I want if user click on the URL then the web page that URL referring to should open in new web browser window.
Asked
Active
Viewed 7,872 times
2

Andrew Thompson
- 168,117
- 40
- 217
- 433

Sandeep Kumar
- 13,799
- 21
- 74
- 110
3 Answers
3
Use JEditorPane with HTMLEditorKit or JTextPane and set content type to "text/html"

StanislavL
- 56,971
- 9
- 68
- 98
-
2See [here](http://stackoverflow.com/questions/6000974/java-jeditorpane-hyperlink-problem/6001047#6001047) for a quick example. ;) – Andrew Thompson May 14 '11 at 09:59
-
I'll try that but I want to know is it possible to achieve this functionality with JTextarea? – Sandeep Kumar May 14 '11 at 10:20
-
@Sandy: I'm afraid it's not possible with JTextArea. – StanislavL May 14 '11 at 12:08
-
This will only allow you to add html content to the JTextPane/jEditorPane. I'm guessing you want the text to be converted into clickabe hyperlink(if it is) as you type. – Igor Oct 13 '12 at 14:03
2
..url referring to should open in new web browser window.
// 1.6+
Desktop.getDesktop().browse(URI);

Andrew Thompson
- 168,117
- 40
- 217
- 433
0
Here is an example of opening links from 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();
}
}
}
}
}
}
});

muramez
- 1
-
1May be you could elaborate a little more about the crucial point in your answer. This can make it possible easier to understand for others. – mle Mar 18 '19 at 15:19