How can I add a clickable URL in a JTextArea?
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.
Use JEditorPane with HTMLEditorKit or JTextPane and set content type to "text/html"
..url referring to should open in new web browser window.
// 1.6+
Desktop.getDesktop().browse(URI);
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();
}
}
}
}
}
}
});
精彩评论