下面列出了怎么用javax.swing.text.html.HTMLDocument的API类实例代码及写法,或者点击链接到github查看源代码。
void checkComposedTextRun() {
HTMLDocument d = (HTMLDocument) ep.getDocument();
ElementIterator it = new ElementIterator(d.getDefaultRootElement());
while (true) {
Element e = it.next();
if (e == null) {
throw new RuntimeException("no composed text found");
}
AttributeSet a = e.getAttributes();
if (a.isDefined(StyleConstants.ComposedTextAttribute)) {
if (!AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute))) {
throw new RuntimeException("AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute)) is false");
}
if (a.isDefined(SwingUtilities2.IMPLIED_CR)) {
throw new RuntimeException("a.isDefined(SwingUtilities2.IMPLIED_CR) is true");
}
return;
}
}
}
private HyperlinkListener createHyperLinkListener() {
return new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e instanceof HTMLFrameHyperlinkEvent) {
((HTMLDocument) html.getDocument()).processHTMLFrameHyperlinkEvent(
(HTMLFrameHyperlinkEvent) e);
} else {
try {
html.setPage(e.getURL());
} catch (IOException ioe) {
System.out.println("IOE: " + ioe);
}
}
}
}
};
}
public static void main(String[] args) throws IOException, InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
MyParser cb = new MyParser();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument)
htmlKit.createDefaultDocument();
FileReader reader = null;
try {
reader = new FileReader(getDirURL() + "test.html");
htmlDoc.getParser().parse(reader, cb, true);
if(failed) {
throw new RuntimeException("Test failed");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public static void main(String[] args) throws Exception {
ParserCB cb = new ParserCB();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlDoc.getParser().parse(new StringReader(text), cb, true);
synchronized (lock) {
if (!isCallbackInvoked) {
lock.wait(5000);
}
}
if (!isCallbackInvoked) {
throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
}
if (exception != null) {
throw exception;
}
}
private static void scrollToId(JEditorPane editor, String id) {
Document d = editor.getDocument();
if (d instanceof HTMLDocument) {
HTMLDocument doc = (HTMLDocument) d;
Element element = doc.getElement(id);
try {
int pos = element.getStartOffset();
// Java 9: Rectangle r = editor.modelToView2D(pos).getBounds();
Rectangle r = editor.modelToView(pos);
if (r != null) {
Rectangle vis = editor.getVisibleRect();
r.height = vis.height;
editor.scrollRectToVisible(r);
editor.setCaretPosition(pos);
}
} catch (BadLocationException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
public static void main(String[] args) throws Exception {
ParserCB cb = new ParserCB();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlDoc.getParser().parse(new StringReader(text), cb, true);
synchronized (lock) {
if (!isCallbackInvoked) {
lock.wait(5000);
}
}
if (!isCallbackInvoked) {
throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
}
if (exception != null) {
throw exception;
}
}
private static void checkImages() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
HTMLEditorKit c = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
try {
c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
} catch (Exception e) {
throw new RuntimeException("The test failed", e);
}
Element elem = doc.getElement("test");
ImageView iv = new ImageView(elem);
if (iv.getLoadingImageIcon() == null) {
throw new RuntimeException("getLoadingImageIcon returns null");
}
if (iv.getNoImageIcon() == null) {
throw new RuntimeException("getNoImageIcon returns null");
}
}
});
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
void checkComposedTextRun() {
HTMLDocument d = (HTMLDocument) ep.getDocument();
ElementIterator it = new ElementIterator(d.getDefaultRootElement());
while (true) {
Element e = it.next();
if (e == null) {
throw new RuntimeException("no composed text found");
}
AttributeSet a = e.getAttributes();
if (a.isDefined(StyleConstants.ComposedTextAttribute)) {
if (!AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute))) {
throw new RuntimeException("AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute)) is false");
}
if (a.isDefined(SwingUtilities2.IMPLIED_CR)) {
throw new RuntimeException("a.isDefined(SwingUtilities2.IMPLIED_CR) is true");
}
return;
}
}
}
public static void main(String[] args) throws Exception {
ParserCB cb = new ParserCB();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlDoc.getParser().parse(new StringReader(text), cb, true);
synchronized (lock) {
if (!isCallbackInvoked) {
lock.wait(5000);
}
}
if (!isCallbackInvoked) {
throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
}
if (exception != null) {
throw exception;
}
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
private static void checkImages() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
HTMLEditorKit c = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
try {
c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
} catch (Exception e) {
throw new RuntimeException("The test failed", e);
}
Element elem = doc.getElement("test");
ImageView iv = new ImageView(elem);
if (iv.getLoadingImageIcon() == null) {
throw new RuntimeException("getLoadingImageIcon returns null");
}
if (iv.getNoImageIcon() == null) {
throw new RuntimeException("getNoImageIcon returns null");
}
}
});
}
private JScrollPane createHTMLPane() {
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
HTMLDocument htmlDocument =
(HTMLDocument) htmlEditorKit.createDefaultDocument();
URL baseURL = getClass().getClassLoader().getResource(("help/help.html"));
htmlDocument.setBase(baseURL);
JEditorPane editor = new JEditorPane();
editor.setEditable(false);
editor.setEditorKit(htmlEditorKit);
try {
String resPath = "help/help.html";
editor.read(getClass().getClassLoader().getResourceAsStream(resPath), htmlDocument);
}
catch (IOException e) {
Main.getInstance().processException(e);
}
return new JScrollPane(editor);
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
private static void checkImages() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
HTMLEditorKit c = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
try {
c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
} catch (Exception e) {
throw new RuntimeException("The test failed", e);
}
Element elem = doc.getElement("test");
ImageView iv = new ImageView(elem);
if (iv.getLoadingImageIcon() == null) {
throw new RuntimeException("getLoadingImageIcon returns null");
}
if (iv.getNoImageIcon() == null) {
throw new RuntimeException("getNoImageIcon returns null");
}
}
});
}
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame("bug8058120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditorKit(new HTMLEditorKit());
document = (HTMLDocument) editorPane.getDocument();
editorPane.setText(text);
frame.add(editorPane);
frame.setSize(200, 200);
frame.setVisible(true);
}
private static void checkImages() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
HTMLEditorKit c = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
try {
c.read(new StringReader("<HTML><TITLE>Test</TITLE><BODY><IMG id=test></BODY></HTML>"), doc, 0);
} catch (Exception e) {
throw new RuntimeException("The test failed", e);
}
Element elem = doc.getElement("test");
ImageView iv = new ImageView(elem);
if (iv.getLoadingImageIcon() == null) {
throw new RuntimeException("getLoadingImageIcon returns null");
}
if (iv.getNoImageIcon() == null) {
throw new RuntimeException("getNoImageIcon returns null");
}
}
});
}
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame("bug8058120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditorKit(new HTMLEditorKit());
document = (HTMLDocument) editorPane.getDocument();
editorPane.setText(text);
frame.add(editorPane);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
public static void main(String[] args) throws IOException, InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
MyParser cb = new MyParser();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument)
htmlKit.createDefaultDocument();
FileReader reader = null;
try {
reader = new FileReader(getDirURL() + "test.html");
htmlDoc.getParser().parse(reader, cb, true);
if(failed) {
throw new RuntimeException("Test failed");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public static void main(String[] args) throws Exception {
int N = 10;
for (int i = 0; i < N; i++) {
HTMLEditorKit kit = new HTMLEditorKit();
Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0);
parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true);
htmlReader.flush();
CharArrayWriter writer = new CharArrayWriter(1000);
kit.write(writer, doc, 0, doc.getLength());
writer.flush();
String result = writer.toString();
if (!result.contains("<tt><a")) {
throw new RuntimeException("The <a> and <tt> tags are swapped");
}
}
}
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame("bug8058120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditorKit(new HTMLEditorKit());
document = (HTMLDocument) editorPane.getDocument();
editorPane.setText(text);
frame.add(editorPane);
frame.setSize(200, 200);
frame.setVisible(true);
}
public HyperlinkListener createHyperLinkListener() {
return new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e instanceof HTMLFrameHyperlinkEvent) {
((HTMLDocument)html.getDocument()).processHTMLFrameHyperlinkEvent(
(HTMLFrameHyperlinkEvent)e);
} else {
try {
html.setPage(e.getURL());
} catch (IOException ioe) {
System.out.println("IOE: " + ioe);
}
}
}
}
};
}
public static void main(String[] args) throws Exception {
ParserCB cb = new ParserCB();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlDoc.getParser().parse(new StringReader(text), cb, true);
synchronized (lock) {
if (!isCallbackInvoked) {
lock.wait(5000);
}
}
if (!isCallbackInvoked) {
throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
}
if (exception != null) {
throw exception;
}
}
/** 构造方法 */
public HTMLDocumentEditor() {
/** 设置主窗体标题 */
super("HTMLDocumentEditor");
HTMLEditorKit editorKit = new HTMLEditorKit();
/** 创建默认文档指向网页引用document */
document = (HTMLDocument) editorKit.createDefaultDocument();
// 强制SWINGSET实现跨平台,不改变风格
try {
UIManager.setLookAndFeel(UIManager
.getCrossPlatformLookAndFeelClassName());
// 如果你想用系统的界面风格替代,请注释掉上一行代码,而取消下一行代码的注释:
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
// 产生异常,则显示错误消息:加载L&F错误
System.err.println("Error loading L&F: " + exc);
}
// 调用初始化方法
init();
}
public void setHRef(int pos, Document doc) {
hRef = null;
text = null;
if (!(doc instanceof HTMLDocument)) {
return;
}
HTMLDocument hdoc = (HTMLDocument) doc;
Iterator iterator = hdoc.getIterator(HTML.Tag.A);
while (iterator.isValid()) {
if (pos >= iterator.getStartOffset() && pos < iterator.getEndOffset()) {
AttributeSet attributes = iterator.getAttributes();
if (attributes != null && attributes.getAttribute(HTML.Attribute.HREF) != null) {
try {
text = hdoc.getText(iterator.getStartOffset(), iterator.getEndOffset() - iterator.getStartOffset()).trim();
hRef = attributes.getAttribute(HTML.Attribute.HREF).toString();
setIndexOfHrefAndText(hdoc, pos, text, hRef);
} catch (BadLocationException e) {
e.printStackTrace();
}
return;
}
}
iterator.next();
}
}
public static void main(String[] args) throws Exception {
ParserCB cb = new ParserCB();
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
htmlDoc.getParser().parse(new StringReader(text), cb, true);
synchronized (lock) {
if (!isCallbackInvoked) {
lock.wait(5000);
}
}
if (!isCallbackInvoked) {
throw new RuntimeException("Test Failed: ParserCallback.handleText() is not invoked for text - " + text);
}
if (exception != null) {
throw exception;
}
}
/**
* This method (as opposed to {@link JEditorPane#scrollToReference}) supports also targets using {@code id} HTML attribute.
*/
public static void scrollToReference(@Nonnull JEditorPane editor, @Nonnull String reference) {
Document document = editor.getDocument();
if (document instanceof HTMLDocument) {
Element elementById = ((HTMLDocument)document).getElement(reference);
if (elementById != null) {
try {
int pos = elementById.getStartOffset();
Rectangle r = editor.modelToView(pos);
if (r != null) {
r.height = editor.getVisibleRect().height;
editor.scrollRectToVisible(r);
editor.setCaretPosition(pos);
}
}
catch (BadLocationException e) {
getLogger().error(e);
}
return;
}
}
editor.scrollToReference(reference);
}
void checkComposedTextRun() {
HTMLDocument d = (HTMLDocument) ep.getDocument();
ElementIterator it = new ElementIterator(d.getDefaultRootElement());
while (true) {
Element e = it.next();
if (e == null) {
throw new RuntimeException("no composed text found");
}
AttributeSet a = e.getAttributes();
if (a.isDefined(StyleConstants.ComposedTextAttribute)) {
if (!AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute))) {
throw new RuntimeException("AbstractDocument.ContentElementName.equals(a.getAttribute(StyleConstants.NameAttribute)) is false");
}
if (a.isDefined(SwingUtilities2.IMPLIED_CR)) {
throw new RuntimeException("a.isDefined(SwingUtilities2.IMPLIED_CR) is true");
}
return;
}
}
}