Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java displaying HTML

Tags:

java

html

swing

I'm trying to display HTML that I received from a server. However, the current code is only working for very few and simple HTML code (e.g. bad request pages).

This is a sample of very simple HTML that I cannot manage to display with my current code.

 <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
 <TITLE>302 Moved</TITLE></HEAD><BODY>
 <H1>302 Moved</H1>
 The document has moved
 <A HREF="http://www.google.be/index.html?gfe_rd=cr&amp;ei=uhoTU6CaDoSNOrHrgeAL">here</A>.
 </BODY></HTML>

Here is my code which runs inside a JFrame.

JEditorPane ed1 = new JEditorPane("text/html", content);
add(ed1);
setVisible(true);
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);

Note that content is just a string with every line of HTML concatenated to one another. Like so: content = "<HTML>.............</HTML>"

There might be more elegant solutions to fetching server responses and displaying them. But, I am restricted to the java.io and java.net packages.

like image 501
xrdty Avatar asked Mar 02 '14 12:03

xrdty


2 Answers

This code writes the HTML to a file and then proceeds to open this file with the default browser.

File file = new File("test.html");
try {
    Files.write(file.toPath(), content.getBytes());
    Desktop.getDesktop().browse(file.toURI());
} catch (IOException e) {
    // TODO Auto-generated catch block
}
like image 156
xrdty Avatar answered Sep 19 '22 23:09

xrdty


The HTML support in JEditorPane is pretty basic, essentially HTML 3.2 with very limited support for styling. You may want to try an alternative renderer component such as flying saucer, which does a much better job of more modern standards such as XHTML and CSS.

like image 23
Ian Roberts Avatar answered Sep 21 '22 23:09

Ian Roberts