import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.Utilities;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
/*
* Created on 06.07.2004
*
* TODO
*/
/**
* @author Administrator TODO Describe what the class is used for
*/
public class JEditorPaneDemo extends JFrame {
private JEditorPane editor;
private JScrollPane scrollPane;
public JEditorPaneDemo() {
super("JEditorPaneDemo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollPane = new JScrollPane();
try {
editor = new JEditorPane("http://www.tutorials.de");
} catch (IOException e) {
e.printStackTrace();
}
editor.setEditable(false);
editor.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
Point p = evt.getPoint();
int offSet = editor.viewToModel(p);
System.out.println(offSet);
Document doc = editor.getDocument();
HTMLDocument htmlDoc = (HTMLDocument) doc;
try {
int pos = Utilities.getWordStart(editor, offSet);
Element elem = Utilities.getParagraphElement(editor, pos);
String url = treeWalk(elem);
if (url != null)
JOptionPane.showMessageDialog(null,
"Du hast auf den Link mit der URL: \n" + url
+ "\n geklickt!");
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
scrollPane.getViewport().add(editor);
getContentPane().add(scrollPane);
setSize(640, 480);
setVisible(true);
}
public static void main(String[] args) {
new JEditorPaneDemo();
}
//Hier gehen wir rekursiv über alle direkt untergeordneten Child-Elemente
// des aktuellen Elements
public String treeWalk(Element elem) {
int cnt = 0;
if ((cnt = elem.getElementCount()) > 0) {
for (int i = 0; i < cnt; i++) {
String ret = treeWalk(elem.getElement(i));
if (ret != null)
return ret;
}
} else {
AttributeSet attributeSet = elem.getAttributes();
Object linkAttr = attributeSet.getAttribute(HTML.Tag.A);
Object hrefAttribute = ((AttributeSet) linkAttr)
.getAttribute(HTML.Attribute.HREF);
if (hrefAttribute != null) {
System.out.println(hrefAttribute);
return (String) hrefAttribute;
}
}
return null;
}
}