Display HTML in JEditorPane
Hi
I am trying to display a String containing HTML text on a JEditorPane.
I have downloaded the HTML from a webpage using sockets, and now I want to display the downloaded page. I have a project in school about sockets.
This is why I can't use getPage(URL);
The following is the code I am using:
String temp = "String with HTML text"
HTMLEditorKit htmlEdKit = new HTMLEditorKit();
JEditorPane.setEditorKit(htmlEdKit);
JEditorPane.setContentType("text/html");
JEditorPane.setEditorKitForContentType("text/html", htmlEdKit);
JEditorPane.setContentType("text");
JEditorPane.setText(temp);
When I run the code, all that is displaying is the raw HTML code, with all the tags. As I understand it, this is how it should be done.
What is wrong, would appreciate some help.
/David Mossberg
it's not necessary to use socket but if use socket get the inputstream from it.
in = socket.getinputstream(); //return inputstream from socket
htmldoc = JEditorPane.getDocument(); //return the htmldoc in JEditorPane
if(htmldoc.getlength()>0)
htmldoc.remove(0,htmlDoc.getLength());//if the htmldoc has some content then remove it
reader = new InputStreamReader(in);//construct a new reader from in
JEditorPane.getEditorKit.read(reader,htmldoc,0); //read new content into the htmldoc from reader
Hope the above code helps you.
joney
Similar Messages
-
Problem to display Animated Gif from HTML into JEditorPane
I have a problem displaying animated gif that comes from URL (HTML) into JEditorPane.
Let me show you the source I have:
* @author Dobromir Gospodinov
* @version 1.0
* Date: Dec 6, 2002
* Time: 6:47:53 PM
package test.advertserver;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JEditorPane ed = new JEditorPane();
try {
ed.setPage("http://localhost:8200/servlet?key=value");
} catch (IOException e) {
e.printStackTrace();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.add(ed);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}Part of the returned from servlet HTML includes an img tag:
<img src="/images/MyAnimatedGif.gif" alt="animated gif comment" width="480" height="50" border="0">Let us assume that MyAnimatedGif.gif has 10 frames and gif is looped - when the 10th is dipslayed it has to display the 1st and so on.
JEditorPane displays frames from 1 to 10 correctly but does not start from the first again. Instead JEditorPane displays a broken image.
I locate where the problem arise:
JEditorPane has an HTMLEditorKit that creates javax.swing.text.html.ImageView instance for every IMG tag.
And here is the problem:
ImageView has an ImageObserver necessary for the asynchronous image download. ImageObserver has the imageUpdate method. But this imageUpdate method is never called with ALLBITS flag raised up. Instead, after the last frame of MyAnimatedGif.gif is downloaded the imageUpdate method is called with flag ERROR raised up. Obviously this is a bug of Sun's implementation. Finaly the flag ALLBITS has to be received for normal end of image observing. But ALLBITS flag does not come.
So, can anybody help me how to load an animated gif within JEditorPane completely.
Thank You in advance,
Dobromir Gospodinov
P.S. If somebody of you wants to debbug what happens within ImageView will have to implement it (and related classes too, because of the limited package visability) borrowing the source from Sun's ImageView.I'm also having this problem with java 1.4.1 I discovered that some animated gifs work fine, while others stop animating. Running with java 1.3.1 fixed the problem. I'm going to report this as a bug
Here's my code:
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class AnimatedGifTester
extends JFrame
public static void main(String argv[])
throws Exception
new AnimatedGifTester();
public AnimatedGifTester()
throws Exception
String[] images = new String[] {
"http://www.gif.com/ImageGallery/Animated/Animals/Photographic/dog_running.gif",
"http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/java.gif",
"http://www.webdeveloper.com/animations/bnifiles/anielg.gif",
"http://www.webdeveloper.com/animations/bnifiles/cat2.gif",
"http://images.animfactory.com/animations/animals/fish/big_fish_swimming_md_wht.gif",
"http://www.webgenies.co.uk/images/martian.gif",
"http://www.webdeveloper.com/animations/bnifiles/at_sign_rotating.gif",
"http://www.webdeveloper.com/animations/bnifiles/arrow_1.gif",
"http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/javaacro.gif",
"http://java.sun.com/products/java-media/2D/samples/suite/Image/duke.running.gif",
"http://www.gif.com/ImageGallery/Animated/SouthPark/Cartoon/stan.gif"
StringBuffer buffer = new StringBuffer("<html><body>");
for (int idx = 0; idx < images.length; idx++)
buffer.append("<img src='" + images[idx] + "'>");
buffer.append("</body></html>");
String html = buffer.toString();
// save a copy of the html to open in a browser so we can see what it's
// supposed to look like
BufferedWriter writer = new BufferedWriter(new FileWriter("animatedGifTest.html"));
writer.write(html);
writer.close();
JEditorPane editorPane = new JEditorPane("text/html", html);
editorPane.setEditable(false);
getContentPane().add(editorPane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(400, 600));
show(); -
JEditorPane not Displaying HTML Correctly
I have a section of code that needs to lookup the HTML for a given URL, and then store the HTML for future use. The problem is the HTML is displaying in the JEditorPane as text rather than rendering it as HTML.
I've stripped the code down as much as possible to work this out. The code to set up the JEditorPane;
jepLocal = new JEditorPane();
jepLocal.setEditable(false);
jepLocal.addHyperlinkListener(new LinkFollower(jepLocal));
// these 2 lines set the jep for syncronous operation ...
JEditorPane.registerEditorKitForContentType( "text/html", "HTMLEditorKit2" );
jepLocal.setEditorKitForContentType( "text/html", new HTMLEditorKit2() );
jepLocal.setPage(urlArray[0]);
htmlString = jepLocal.getText();
I'm using a simple class to set the jep into syncronous mode for retrieval. Here is that class;
class HTMLEditorKit2 extends HTMLEditorKit{
public Document createDefaultDocument(){
HTMLDocument myDocument = (HTMLDocument)(super.createDefaultDocument());
myDocument.setAsynchronousLoadPriority(-1); // load synchronously
return myDocument;
}The code runs in it's own thread, in case that matters.
Can anyone see what is wrong with this setup? When I feed the htmlString into another jep, I get text display of the html rather than rendered.
BernieWhen I feed the htmlString into another jep, I gettext display of the html rather than rendered.
How are you "feed[ing] the htmlString into another
jep?" Does the other JEditorPane know it's text/html
rather than text/plain?
myThis.getEditorPane().setText(htmlString);The other jep is in the main gui thread. It loades web pages fine when it's handed a URL and the extracted HTML can be saved and redisplayed using the setText method like above. This jep has all the same setup code, including the EditorKit inclusion.
Bernie -
Help -- How to display Html text in a JEditorPane
I'm trying to display html in a JEditorPane (html is obtained by transforming Xml and Xsl). So after i do the transformation i have a string which is the html source to be displayed. But when i use editorpane.setText(htmlString) method it is displaying the html source in the editorpane. I also tried using the HTMLEditorKit's read method. Even then its displaying the html source. But when i store the html source as a html file and give the editorpane, the url of the html file, it displays properly.
I would be so grateful if u can help in displaying the html (which i have as a string) instead of the source...
Thank you so much...Hi, after struggling with problem, the solution seems to be to ditch the content type meta tag, JEditorPane seems to barf (silently!) on this...
So, to turn this off...
transformer.setOutputProperty(OutputKeys.ENCODING,"");
Cheers
Greg -
Displaying HTML character entities in JEditorPane
Hi,
I have noticed that when displaying HTML character entity references in a JEditorPane it will show some of them, e.g. © for copyright symbol but not others e.g. ’ for "curly" single quote.
Is there any way to get JEditorPane to show all (most?) of them?Create a class that extends ComboBox and override the
updateDisplayList and measureText functions. Then use that new
ComboBox in your code:
<local:HtmlComboBox .. xmlns:local="components.*".>
<local:itemRenderer>
<mx:Component>
<mx:Text htmlText="{data.label}" />
</mx:Component>
</local:itemRenderer>
</local:HtmlComboBox>
Put this into a folder called "components" and name the file
HtmlComboBox.as
package components
import mx.controls.ComboBox;
import flash.text.TextLineMetrics;
public class HtmlComboBox extends ComboBox
public function HtmlComboBox()
super();
override protected function
updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
super.updateDisplayList(unscaledWidth,unscaledHeight);
var s:String = textInput.text;
textInput.htmlText = s;
override public function
measureText(text:String):TextLineMetrics
return measureHTMLText(text);
} -
Regarding displaying html page in a JEditorPane
i want to display a html page in a JEditorPane but the problem is it is displying the page but the script part of html page is printed as it is in the pane . please tell the solution for it . i will be highly thankful to u.
What you are doing exactly? you are displaying the html file into a JEditorPane or After displaying you are tring to Print it out in the Paper or what.
If this the First Sinario then this code will help you.
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class Htmlexample extends JInternalFrame {
//Constructor of Class.
public Htmlexample () {
//super(Title, Resizable, Closable, Maximizable, Iconifiable)
super (title, true, true, true, true);
setSize (500, 350);
HtmlPane html = new HtmlPane ("Help/Keys.htm");
setContentPane (html);
setVisible (true);
//Following Class Show HTML Help inside an EditorPane.
class HtmlPane extends JScrollPane implements HyperlinkListener {
JEditorPane html;
public HtmlPane (String filename) {
try {
File f = new File (filename);
String s = f.getAbsolutePath();
s = "file:" + s;
URL url = new URL (s);
html = new JEditorPane (s);
html.setEditable (false);
html.addHyperlinkListener (this);
JViewport vp = getViewport();
vp.add (html);
catch (MalformedURLException e) { }
catch (IOException e) { }
//Function Perform By the HyperLinks of HTML Help File.
public void hyperlinkUpdate (HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
linkActivated (e.getURL());
//Function for Loading other HTML Pages in Your HTML Help.
protected void linkActivated (URL u) {
Cursor c = html.getCursor();
Cursor waitCursor = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
html.setCursor (waitCursor);
SwingUtilities.invokeLater (new PageLoader (u, c));
//Following Class Load Other Pages Included in Our HTML Help File.
class PageLoader implements Runnable {
//Constructor of Class.
PageLoader (URL u, Cursor c) {
url = u;
cursor = c;
public void run () {
if (url == null) {
html.setCursor (cursor);
Container parent = html.getParent();
parent.repaint();
else {
Document doc = html.getDocument();
try {
html.setPage (url);
catch (IOException ioe) {
html.setDocument (doc);
getToolkit().beep();
finally {
url = null;
SwingUtilities.invokeLater (this);
URL url;
Cursor cursor;
}if there is any other issue Let me Know
Thank you
Jofin -
JEditorPane doesn�t display HTML special char. codes
My application is using JEditorPane to display text/html.
The problem comes when I try to display HTML special character codes such as
> JEditorPane ignores those codes and displays nothing.
Do I have to convert all those strings representing special characters?
How could I solve it?
Thanks in advance,
BrunoHere's my solution - I replace the HTMLEditorKit if it's not the first pass through. I found that the EditorKit is an instance of HTMLEditorKit for every pass except the first (which doesn't have a problem).
EditorKit ek = displayJEditorPane.getEditorKit();
if( ek instanceof HTMLEditorKit ) {
// Needs to be replaced
HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
displayJEditorPane.setEditorKit( htmlEditorKit );
// Display the HTML document
displayJEditorPane.setPage( resultURL );I'll spread my Duke Dollars around to everyone who offered a suggestion later today if I don't hear of a better solution.
Thanks. -
JEditorPane displays html font very large.
I have a JEditroPane embedded into a JScrollPane. The url for the EditorPane is an html file. It laods and displays. However, my html font is set to 8 but what is displayed appears to be at 12 point or higher. Is there a way to alter the font size of the html text displayed inside the JEditorPane?
Thanks.Can anyone explain how to change the font size for the
entire html document set to the JEditorPane? The
default size is too large and any attmept to perform a
setFontSize fails.
Thanks.I'm posting this to save you time by letting you give up hope on finding some simple solution to your problem.
There may not be any.
I've just tried loading my html file into a JEditorPane and all characters appear in default regular size. It seems JEditorPane is not processing any stylesheets info which I use to define all text attributes.
The API document says:
"text/html
HTML text. The kit used in this case is the class javax.swing.text.html.HTMLEditorKit which provides HTML 3.2 support. "
3.2 is pretty old, isn't it? What's the HTML version you used to create your HTML files?
How do you set font size in your html files? A sample html file from Sun for a Text demo program uses the following and it seems to work:
<font size=-2>from</font> a
<font size=+2">URL</font>
If you decide to modify your existing HTML files, use the above format.
(Wait! Why do we need to modify perfectly working html files to make them appear normal in Java programs? It should be the other way around! :D) -
Hello
I am having trouble with displaying HTML with image maps in JEditorPane component. I am trying to load a simple html file as follows:
<html>
<IMG SRC="monk.gif" HEIGHT="255" WIDTH="262" ISMAP USEMAP="#mapareas">
<map NAME="mapareas">
<area SHAPE=CIRCLE COORDS="107,158 132,162" HREF="basic.htm" ALT="Basic Page">
<area SHAPE=default HREF="index.html">
</MAP>
</html>
There is no problem with displaying the image. It's rendered fine without any problem. But, When I click on the circle area, I can't seem to get the URL corresponding to the map area. I tried the HyperlinkEvent::getDescription() and HyperlinkEvent::getURL() methods and both of them return the reference to the map as opposed to the reference specified for the specific map area ( in my case, "sample.map" instead of "basic.htm" ).
Can someone tell me if HTML with image maps is supported in EditorPane? if so, how do I get the reference to the map area clicked?
thanks in adv
Venkat KotaJTextComponent.viewToModel
then get the element at that location, either the character or
paragraph element, then get its StyleContext.NameAttribute value, which is a HTML.Tag.
That was a fun walk round the API, to find out more, I recomend reading through JTextComponent, and its Model/View Split section.
The the Element and View interfaces. -
How to load file.html in JEditorPane
Hello
how to display HTML file including images in JEditorPane
the file is on local system
thanksThis is how I read contents of a file and put it into my JEditorPane.
I don't know if it will incliude images or not, but it might.
try {
editorPane1.read(new FileReader(getFile),null);
catch(IOException e)
e.printStackTrace();
-
Displaying HTML in a java application
Is there any other way to display HTML in a java application besides JEditorPane and JLabel (which are fairly restrictive). Its tableing I'm really after.
Eureka!
http://home.earthlink.net/~hheister/ -
Any Way to display HTML pages on Applet
Hi All,
Is there any way to show web pages on Applet?
Is it possible ?I am not aware of a simple way to display HTML in an applet. However, I have used the JEditorPane to display HTML documents. Handling links, etc. with this component requires some effort. Also requires Swing.
Have you considered using the applet to display a page on the browser. (i.e. getAppletContext().showDocument(URL, [frame name]))? Just an idea.
Good luck. -
Web Page Display alternitives to JEditorPane
The JEditorPane doesn't display HTML very well, Even the simplest sites are messed up, but it can be great for other things.
If I wanted to write a web browser in Java, what component would I use to display HTML web pages, and have them displayed more properly than the JEditorPane?
Do I have to roll out my own custom Swing component for that kind of thing?I regret to say that you can't really rely on any of the standard swing components for this purpose. The html support given in JEditorPane isn't even rudimentary. You'll have to provide your own swing component to do that, however, several other people have already done some work in this field.
Take a look at https://xhtmlrenderer.dev.java.net/ for instance. Another good idea would be enclosing webkit in an AWT component. -
I want display html file using JEditorPane
but I become an exception
java.net.MalformedURLException: unknown protocol: e
what schould be the problem
import javax.swing.*;
import java.net.URL;
import java.io.File;
public class Browser extends JFrame
JEditorPane ePane = new JEditorPane();
public Browser(){
this.setBounds(200,50,700,650);
this.setLayout(null);
ePane.setBounds(50,20, 600,500);
try {
File file = new File("xx.html");
String ss = file.getAbsolutePath();
URL url = new URL(ss);
ePane.setPage(url);
} catch (java.io.IOException ex) { ex.printStackTrace(); }
this.add(ePane);
}File file = new File("xx.html");"xx.html" lacks a protocol, like "http" or "ftp". But anyway, why not just use File.toURL()?
-
How Do I Display HTML Formatted Text From A Data Table In Crystal Reports?
I'm creating reports in Crystal XI. The information being displayed in the reports comes from data tables where the text is formatted in HTML.
I've worked with Crystal Reports enough to know that HTML text pulled from a data table doesn't appear in Crystal the same way it does in a web browser. Crystal Reports ignores all the tags (...unless I'm missing something...) and just displays the text.
Someone far more Crystal savy than I (...who I don't have access to...) came up with a Formula Field workaround that tricks Crystal Reports into displaying some basic HTML tags. Here's that workaround:
<!--
stringVar TableName := ;
TableName := Replace (TableName, "<ul>","<br> <br>");
TableName := Replace (TableName, "<li>", "<br> • ");
TableName := Replace (TableName, "</li>", "");
TableName := Replace (TableName, "</ul>","<br> <br>");
TableName := Replace (TableName, "<a", "<u><font color='blue'");
TableName := Replace (TableName, "</a>", "</font></u>");
TableName
-->
QUESTION - Does any similar workaround exist so I can display an HTML Table in Crystal Reports? If not, is there any way to display HTML formatted text from a data table in Crystal Reports as it would appear in a web browser?Hi Steven,
To display html text in Crystal Reports follows these steps.
1. Right click on the field and select Paragraph tab.
2. Under 'Text Interpretation' select 'HTML Text' and click OK.
I have tried using the way,but it never works.So reply me if there is any way to solve the issue
Maybe you are looking for
-
"Your computer restarted because there was a problem"
Over the last week or so, I've had issues with my system suddenly restarting. I have not been able to conclude any common symptoms when this happens and this issue is becoming more and more common to the point where it is happening multiple times wit
-
I need a flash tutorial on Iphone style Scrolling Photo Gallery using Next/previous Buttons
Here i have attached two sample Fla files of iphone style scrolling photo gallery using next Previous buttons. Smoothscroller.fla is the original file download from internet and thumbscroll.fla is the one i m trying to make. But i m getting the act
-
Hey I have a problem making TREX search for documents in my content server. I have made some Content Repositories where i want to perform my search. What I have done so far, is to make a CM Repository for the Content Repository with Persistence Mode
-
How to create sequence in control file from command prompt.
-
Email sent but cant find it on sent folders, drafts or anywhere?
Email sent but cant find it on sent folders, drafts or anywhere, have a message sitting in drats that says message upload incomplete..