下面列出了怎么用javax.swing.text.html.HTMLEditorKit的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Extract all A-HREF contained URLS from the given URL and return in List
*/
public ArrayList extract(String url) throws IOException {
if (debug)
System.out.println(" URLextract=" + url);
baseURL = new URL(url);
InputStream in = baseURL.openStream();
InputStreamReader r = new InputStreamReader(filterTag(in), CDM.UTF8);
HTMLEditorKit.ParserCallback callback = new CallerBacker();
urlList = new ArrayList();
wantURLS = true;
wantText = false;
parser.parse(r, callback, false);
return urlList;
}
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 createAndShowGUI(String text) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editorPane = new JEditorPane();
HTMLEditorKit editorKit = new HTMLEditorKit();
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
editorPane.setCaretPosition(1);
frame.add(editorPane);
frame.setSize(200, 200);
frame.setVisible(true);
}
});
}
private static String convertToRTF(final String htmlStr) {
OutputStream os = new ByteArrayOutputStream();
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
RTFEditorKit rtfEditorKit = new RTFEditorKit();
String rtfStr = null;
String tempStr = htmlStr.replace("</font>", "#END_FONT#").replace("<br>", "#NEW_LINE#");
InputStream is = new ByteArrayInputStream(tempStr.getBytes());
try {
Document doc = htmlEditorKit.createDefaultDocument();
htmlEditorKit.read(is, doc, 0);
rtfEditorKit.write(os, doc, 0, doc.getLength());
rtfStr = os.toString();
rtfStr = rtfStr.replace("#NEW_LINE#", "\\line ");
rtfStr = rtfStr.replace("#END_FONT#", "\\cf0 ");
} catch (IOException | BadLocationException e) {
e.printStackTrace();
}
return rtfStr;
}
public static HTMLDocument loadHtml(BufferedReader br){
//String html){//
try {
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
doc.putProperty("IgnoreCharsetDirective"
,Boolean.TRUE);//, new Boolean(true));
kit.read(br, doc, 0);
br.close();
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
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 {
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 createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
HTMLEditorKit editorKit = new HTMLEditorKit();
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
frame.add(editorPane);
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");
}
}
}
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 {
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;
}
}
@Override
protected JPanel createTextPanel(String message) {
if (message != null && message.toLowerCase().startsWith("<html>")) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setName("MESSAGE-COMPONENT");
editorPane.setText(message);
editorPane.setBackground(new GLabel().getBackground());
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JScrollPane scrollPane = new JScrollPane(editorPane);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
panel.add(scrollPane);
return panel;
}
return super.createTextPanel(message);
}
private static void createAndShowGUI(String text) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editorPane = new JEditorPane();
HTMLEditorKit editorKit = new HTMLEditorKit();
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
editorPane.setCaretPosition(1);
frame.add(editorPane);
frame.setSize(200, 200);
frame.setVisible(true);
}
});
}
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
HTMLEditorKit editorKit = new HTMLEditorKit();
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
frame.add(editorPane);
frame.setVisible(true);
}
private static void createAndShowGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane editorPane = new JEditorPane();
HTMLEditorKit editorKit = new HTMLEditorKit();
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
frame.add(editorPane);
frame.setVisible(true);
}
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 PreviewView(ReportEditorView reportEditorView) {
this.reportEditorView = reportEditorView;
JScrollPane pane = new JScrollPane(editorPane);
HTMLEditorKit kit = new HTMLEditorKit() {
/**
*
*/
private static final long serialVersionUID = -8040272164224951314L;
@Override
public Document createDefaultDocument() {
Document document = super.createDefaultDocument();
document.putProperty("IgnoreCharsetDirective", true);
return document;
}
};
editorPane.setEditorKit(kit);
editorPane.setEditable(false);
this.add(pane, BorderLayout.CENTER);
}
/**
* Given some html, extracts its text.
*/
public static String extractTextFromHTML(String html) {
try {
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet handle charset's properly.
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
// Create a reader on the HTML content.
Reader rd = new StringReader(html);
// Parse the HTML.
kit.read(rd, doc, 0);
// The HTML text is now stored in the document
return doc.getText(0, doc.getLength());
} catch (Exception e) {
}
return "";
}
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 void postInitComponents () {
this.jLabel2.setVisible(false);
this.platformHome.setVisible(false);
final Collection installFolders = platform.getInstallFolderURLs();
if (platform.getInstallFolders().isEmpty() && installFolders.size() > 0) {
this.jLabel2.setVisible(true);
this.platformHome.setVisible(true);
this.platformHome.setForeground(new Color (164,0,0));
this.platformHome.setText (Utilities.toFile(URI.create(((URL)installFolders.iterator().next()).toExternalForm())).getAbsolutePath());
}
HTMLEditorKit htmlkit = new HTMLEditorKit();
StyleSheet css = htmlkit.getStyleSheet();
if (css.getStyleSheets() == null) {
StyleSheet css2 = new StyleSheet();
Font f = jLabel2.getFont();
css2.addRule(new StringBuffer("body { font-size: ").append(f.getSize()) // NOI18N
.append("; font-family: ").append(f.getName()).append("; }").toString()); // NOI18N
css2.addStyleSheet(css);
htmlkit.setStyleSheet(css2);
}
jTextPane1.setEditorKit(htmlkit);
jTextPane1.setText(NbBundle.getMessage(BrokenPlatformCustomizer.class,"MSG_BrokenProject"));
}
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");
}
}
}
@Override public ViewFactory getViewFactory() {
return new HTMLEditorKit.HTMLFactory() {
@Override public View create(Element elem) {
View view = super.create(elem);
if (view instanceof LabelView) {
System.out.println("debug: " + view.getAlignment(View.Y_AXIS));
}
AttributeSet attrs = elem.getAttributes();
Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
Object o = Objects.nonNull(elementName) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag kind = (HTML.Tag) o;
if (kind == HTML.Tag.IMG) {
return new ImageView(elem) {
@Override public float getAlignment(int axis) {
// .8125f magic number...
return axis == View.Y_AXIS ? .8125f : super.getAlignment(axis);
}
};
}
}
return view;
}
};
}
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 IntroWindow() {
this.setIconImages(Resources.iconList);
setSize(new Dimension(800, 800));
setType(Type.UTILITY);
setTitle("JDA - Help");
getContentPane().setLayout(new CardLayout(0, 0));
this.setResizable(false);
this.setLocationRelativeTo(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBar(null);
getContentPane().add(scrollPane);
editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setContentType("text/html");
editorPane.setEditable(false);
try {
editorPane.setText(IOUtils.toString(Resources.class.getResourceAsStream("/club/bytecode/the/jda/html/intro.html"), "UTF-8"));
} catch (IOException e) {
System.err.println("Couldn't load intro html:");
e.printStackTrace();
}
scrollPane.setViewportView(editorPane);
}
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");
}
}
});
}
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 void setHtmlText(String htmlText) {
htmlText = htmlText.replaceAll("\n", "<br/>");
editorPane.setContentType("text/html; charset=utf-8");
HTMLEditorKit kit = new HTMLEditorKit();
editorPane.setEditorKit(kit);
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("span{background-color:#FBC87A;color:2B2B2B}");
styleSheet.addRule("body{font-family:" + findResultCount.getFont().getName() + ";font-size:" + findResultCount.getFont().getSize() + ";}");
editorPane.setText(htmlText);
editorPane.setCaretPosition(0);
}