SetDocument() in an JEditorPane
Hi,
I am using a JEditorPane to display some HTML. When I try to setDocument() with a HTMLDocument, I get a NullPointerException. Any ideas what the problem could be?
msgArea = new JEditorPane("text/html", "");
htmlDoc = (HTMLDocument)((HTMLEditorKit)msgArea.getEditorKit()).createDefaultDocument();
attr = ((HTMLEditorKit)msgArea.getEditorKit()).getInputAttributes();
msgArea.setDocument(htmlDoc); //--- throws the Exception
Exception occurred during event dispatching:
java.lang.NullPointerException
at javax.swing.text.html.StyleSheet.getRule(Unknown Source)
at javax.swing.text.html.StyleSheet$ViewAttributeSet.<init>(Unknown Source)
at javax.swing.text.html.StyleSheet.getViewAttributes(Unknown Source)
at javax.swing.text.html.BlockView.setPropertiesFromAttributes(Unknown Source)
at javax.swing.text.html.BlockView.setParent(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.setView(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.setView(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.modelChanged(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.propertyChange(Unknown Source)
at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
at javax.swing.JComponent.firePropertyChange(Unknown Source)
at javax.swing.text.JTextComponent.setDocument(Unknown Source)Thanks,
Dewang
At first look, it seems that htmlDoc has a null value, which is not the case :|
I tested this code, and made one change, which is
msgArea = new JEditorPane();
msgArea.setContentType("text/html");
and it works fine :).
Similar Messages
-
Help with code to print HTML in Java 5
Hi,
The following code works and runs successfully..
However, the printing in Java 1.4.2_03 is better than Java 5 (latest version).
i.e in particular the characters are not monospaced compared with compiling with Java 1.4.2_03. e.g si so ss squashed together.
This issue does not seem to occur when running the same code in Java 1.4.2_03. (I haven't tried other 1.4.2 java versions).
Any help would be appreciated. We really need this working under Java 5 or bust.
Here is the complete listing ... PrintHtml.java (it uses the DocumentRenderer)
and following this is the input file.
import javax.swing.text.html.HTMLDocument;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.InputStream;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.lang.reflect.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JEditorPane;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.View;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
import java.text.ParseException;
public class PrintHtml {
* Utility helper to convert HTML Text to HTML Document.
* @param baseUrl URL to be used in order
* to resolve relative HTML references, in lieu of an
* HTML BASE tag. May be null, if not required or HTML
* BASE tag is to be used.
* @see jbox.view.jfx.JboxHtmlEditor
* @see jbox.utility.JboxPrint
* @see jbox.utility.JboxPrintUtil
public static HTMLDocument htmlTextToHtmlDoc(String htmlText, URL baseUrl)
try
// JboxHtmlEditorKit editorKit = new JboxHtmlEditorKit();
HTMLEditorKit editorKit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)editorKit.createDefaultDocument();
if (baseUrl != null)
try
doc.setBase(baseUrl);
catch(Exception e)
//JboxTraceManager.trace(e);
StringReader reader = new StringReader(htmlText);
editorKit.read(reader, doc, 0);
return doc;
catch(Exception e)
//JboxTraceManager.trace(e);
return null;
public static void main(String[] args) {
System.out.println("printing...");
HTMLDocument x = new HTMLDocument();
DocumentRenderer invoice = new DocumentRenderer();
//invoice.setScaleWidthToFit(false);
String s = "";
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("mark.html"));
InputStreamReader in = new InputStreamReader(bis , "ASCII");
StringWriter sw = new StringWriter();
while (true) {
int datum = in.read();
if (datum == -1) break;
sw.write(datum);
in.close();
s = sw.toString();
System.out.println("s="+s);
catch (IOException e) {
System.err.println(e);
HTMLDocument htmldoc = htmlTextToHtmlDoc(s, null);
invoice.print(htmldoc);
// the good old infamous DocumentRenderer.
/* Copyright 2002
Kei G. Gauthier
Suite 301
77 Winsor Street
Ludlow, MA 01056
class DocumentRenderer implements Printable {
/* DocumentRenderer prints objects of type Document. Text attributes, including
fonts, color, and small icons, will be rendered to a printed page.
DocumentRenderer computes line breaks, paginates, and performs other
formatting.
An HTMLDocument is printed by sending it as an argument to the
print(HTMLDocument) method. A PlainDocument is printed the same way. Other
types of documents must be sent in a JEditorPane as an argument to the
print(JEditorPane) method. Printing Documents in this way will automatically
display a print dialog.
As objects which implement the Printable Interface, instances of the
DocumentRenderer class can also be used as the argument in the setPrintable
method of the PrinterJob class. Instead of using the print() methods
detailed above, a programmer may gain access to the formatting capabilities
of this class without using its print dialog by creating an instance of
DocumentRenderer and setting the document to be printed with the
setDocument() or setJEditorPane(). The Document may then be printed by
setting the instance of DocumentRenderer in any PrinterJob.
protected int currentPage = -1; //Used to keep track of when
//the page to print changes.
protected JEditorPane jeditorPane; //Container to hold the
//Document. This object will
//be used to lay out the
//Document for printing.
protected double pageEndY = 0; //Location of the current page
//end.
protected double pageStartY = 0; //Location of the current page
//start.
protected boolean scaleWidthToFit = true; //boolean to allow control over
//whether pages too wide to fit
//on a page will be scaled.
/* The DocumentRenderer class uses pFormat and pJob in its methods. Note
that pFormat is not the variable name used by the print method of the
DocumentRenderer. Although it would always be expected to reference the
pFormat object, the print method gets its PageFormat as an argument.
protected PageFormat pFormat;
protected PrinterJob pJob;
/* The constructor initializes the pFormat and PJob variables.
public DocumentRenderer() {
pFormat = new PageFormat();
pJob = PrinterJob.getPrinterJob();
/* Method to get the current Document
public Document getDocument() {
if (jeditorPane != null) return jeditorPane.getDocument();
else return null;
/* Method to get the current choice the width scaling option.
public boolean getScaleWidthToFit() {
return scaleWidthToFit;
/* pageDialog() displays a page setup dialog.
public void pageDialog() {
pFormat = pJob.pageDialog(pFormat);
/* The print method implements the Printable interface. Although Printables
may be called to render a page more than once, each page is painted in
order. We may, therefore, keep track of changes in the page being rendered
by setting the currentPage variable to equal the pageIndex, and then
comparing these variables on subsequent calls to this method. When the two
variables match, it means that the page is being rendered for the second or
third time. When the currentPage differs from the pageIndex, a new page is
being requested.
The highlights of the process used print a page are as follows:
I. The Graphics object is cast to a Graphics2D object to allow for
scaling.
II. The JEditorPane is laid out using the width of a printable page.
This will handle line breaks. If the JEditorPane cannot be sized at
the width of the graphics clip, scaling will be allowed.
III. The root view of the JEditorPane is obtained. By examining this root
view and all of its children, printView will be able to determine
the location of each printable element of the document.
IV. If the scaleWidthToFit option is chosen, a scaling ratio is
determined, and the graphics2D object is scaled.
V. The Graphics2D object is clipped to the size of the printable page.
VI. currentPage is checked to see if this is a new page to render. If so,
pageStartY and pageEndY are reset.
VII. To match the coordinates of the printable clip of graphics2D and the
allocation rectangle which will be used to lay out the views,
graphics2D is translated to begin at the printable X and Y
coordinates of the graphics clip.
VIII. An allocation Rectangle is created to represent the layout of the
Views.
The Printable Interface always prints the area indexed by reference
to the Graphics object. For instance, with a standard 8.5 x 11 inch
page with 1 inch margins the rectangle X = 72, Y = 72, Width = 468,
and Height = 648, the area 72, 72, 468, 648 will be painted regardless
of which page is actually being printed.
To align the allocation Rectangle with the graphics2D object two
things are done. The first step is to translate the X and Y
coordinates of the graphics2D object to begin at the X and Y
coordinates of the printable clip, see step VII. Next, when printing
other than the first page, the allocation rectangle must start laying
out in coordinates represented by negative numbers. After page one,
the beginning of the allocation is started at minus the page end of
the prior page. This moves the part which has already been rendered to
before the printable clip of the graphics2D object.
X. The printView method is called to paint the page. Its return value
will indicate if a page has been rendered.
Although public, print should not ordinarily be called by programs other
than PrinterJob.
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
double scale = 1.0;
Graphics2D graphics2D;
View rootView;
// I
graphics2D = (Graphics2D) graphics;
disableDoubleBuffering(jeditorPane);
// II
jeditorPane.setSize((int) pageFormat.getImageableWidth(),Integer.MAX_VALUE);
jeditorPane.validate();
// III
rootView = jeditorPane.getUI().getRootView(jeditorPane);
// IV
if ((scaleWidthToFit) && (jeditorPane.getMinimumSize().getWidth() >
pageFormat.getImageableWidth())) {
scale = pageFormat.getImageableWidth()/
jeditorPane.getMinimumSize().getWidth();
graphics2D.scale(scale,scale);
// V
graphics2D.setClip((int) (pageFormat.getImageableX()/scale),
(int) (pageFormat.getImageableY()/scale),
(int) (pageFormat.getImageableWidth()/scale),
(int) (pageFormat.getImageableHeight()/scale));
// VI
if (pageIndex > currentPage) {
currentPage = pageIndex;
pageStartY += pageEndY;
pageEndY = graphics2D.getClipBounds().getHeight();
// VII
graphics2D.translate(graphics2D.getClipBounds().getX(),
graphics2D.getClipBounds().getY());
// VIII
Rectangle allocation = new Rectangle(0,
(int) -pageStartY,
(int) (jeditorPane.getMinimumSize().getWidth()),
(int) (jeditorPane.getPreferredSize().getHeight()));
// X
if (printView(graphics2D,allocation,rootView)) {
return Printable.PAGE_EXISTS;
else {
pageStartY = 0;
pageEndY = 0;
currentPage = -1;
return Printable.NO_SUCH_PAGE;
/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on.
* So this turns if off globally.
* @see enableDoubleBuffering
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
/** Re-enables double buffering globally. */
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
/* print(HTMLDocument) is called to set an HTMLDocument for printing.
public void print(HTMLDocument htmlDocument) {
setDocument(htmlDocument);
printDialog();
/* print(JEditorPane) prints a Document contained within a JEDitorPane.
public void print(JEditorPane jedPane) {
setDocument(jedPane);
printDialog();
/* print(PlainDocument) is called to set a PlainDocument for printing.
public void print(PlainDocument plainDocument) {
setDocument(plainDocument);
printDialog();
/* A protected method, printDialog(), displays the print dialog and initiates
printing in response to user input.
protected void printDialog() {
if (pJob.printDialog()) {
pJob.setPrintable(this,pFormat);
try {
pJob.print();
catch (PrinterException printerException) {
pageStartY = 0;
pageEndY = 0;
currentPage = -1;
System.out.println("Error Printing Document");
/* printView is a recursive method which iterates through the tree structure
of the view sent to it. If the view sent to printView is a branch view,
that is one with children, the method calls itself on each of these
children. If the view is a leaf view, that is a view without children which
represents an actual piece of text to be painted, printView attempts to
render the view to the Graphics2D object.
I. When any view starts after the beginning of the current printable
page, this means that there are pages to print and the method sets
pageExists to true.
II. When a leaf view is taller than the printable area of a page, it
cannot, of course, be broken down to fit a single page. Such a View
will be printed whenever it intersects with the Graphics2D clip.
III. If a leaf view intersects the printable area of the graphics clip and
fits vertically within the printable area, it will be rendered.
IV. If a leaf view does not exceed the printable area of a page but does
not fit vertically within the Graphics2D clip of the current page, the
method records that this page should end at the start of the view.
This information is stored in pageEndY.
protected boolean printView(Graphics2D graphics2D, Shape allocation,
View view) {
boolean pageExists = false;
Rectangle clipRectangle = graphics2D.getClipBounds();
Shape childAllocation;
View childView;
if (view.getViewCount() > 0 &&
!view.getElement().getName().equalsIgnoreCase("td")) {
for (int i = 0; i < view.getViewCount(); i++) {
childAllocation = view.getChildAllocation(i,allocation);
if (childAllocation != null) {
childView = view.getView(i);
if (printView(graphics2D,childAllocation,childView)) {
pageExists = true;
} else {
// I
if (allocation.getBounds().getMaxY() >= clipRectangle.getY()) {
pageExists = true;
// II
if ((allocation.getBounds().getHeight() > clipRectangle.getHeight()) &&
(allocation.intersects(clipRectangle))) {
view.paint(graphics2D,allocation);
} else {
// III
if (allocation.getBounds().getY() >= clipRectangle.getY()) {
if (allocation.getBounds().getMaxY() <= clipRectangle.getMaxY()) {
view.paint(graphics2D,allocation);
} else {
// IV
if (allocation.getBounds().getY() < pageEndY) {
pageEndY = allocation.getBounds().getY();
return pageExists;
/* Method to set the content type the JEditorPane.
protected void setContentType(String type) {
jeditorPane.setContentType(type);
/* Method to set an HTMLDocument as the Document to print.
public void setDocument(HTMLDocument htmlDocument) {
jeditorPane = new JEditorPane();
setDocument("text/html",htmlDocument);
/* Method to set the Document to print as the one contained in a JEditorPane.
This method is useful when Java does not provide direct access to a
particular Document type, such as a Rich Text Format document. With this
method such a document can be sent to the DocumentRenderer class enclosed
in a JEditorPane.
public void setDocument(JEditorPane jedPane) {
jeditorPane = new JEditorPane();
setDocument(jedPane.getContentType(),jedPane.getDocument());
/* Method to set a PlainDocument as the Document to print.
public void setDocument(PlainDocument plainDocument) {
jeditorPane = new JEditorPane();
setDocument("text/plain",plainDocument);
/* Method to set the content type and document of the JEditorPane.
protected void setDocument(String type, Document document) {
setContentType(type);
jeditorPane.setDocument(document);
/* Method to set the current choice of the width scaling option.
public void setScaleWidthToFit(boolean scaleWidth) {
scaleWidthToFit = scaleWidth;
}The sample input file is "mark.html":::
<html>
<head>
<style type="text/css">
<!--
ol { list-style-type: decimal; margin-top: 10; margin-left: 50; margin-bottom: 10 }
u { text-decoration: underline }
s { text-decoration: line-through }
p { font-weight: normal; font-size: medium; margin-top: 15 }
dd p { margin-top: 0; margin-left: 40; margin-bottom: 0 }
ol li p { margin-top: 0; margin-bottom: 0 }
address { color: blue; font-style: italic }
i { font-style: italic }
h6 { font-weight: bold; font-size: xx-small; margin-top: 10; margin-bottom: 10 }
h5 { font-weight: bold; font-size: x-small; margin-top: 10; margin-bottom: 10 }
h4 { font-weight: bold; font-size: small; margin-top: 10; margin-bottom: 10 }
h3 { font-weight: bold; font-size: medium; margin-top: 10; margin-bottom: 10 }
dir li p { margin-top: 0; margin-bottom: 0 }
h2 { font-weight: bold; font-size: large; margin-top: 10; margin-bottom: 10 }
b { font-weight: bold }
h1 { font-weight: bold; font-size: x-large; margin-top: 10; margin-bottom: 10 }
a { color: blue; text-decoration: underline }
ul li ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
menu { margin-top: 10; margin-left: 40; margin-bottom: 10 }
menu li p { margin-top: 0; margin-bottom: 0 }
table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
sup { vertical-align: sup }
body { margin-right: 0; font-size: 14pt; font-family: SansSerif; color: black; margin-left: 0 }
ul li ul li ul { list-style-type: square; margin-left: 25 }
blockquote { margin-right: 35; margin-top: 5; margin-left: 35; margin-bottom: 5 }
samp { font-size: small; font-family: Monospaced }
cite { font-style: italic }
sub { vertical-align: sub }
em { font-style: italic }
table table table { border-color: Gray; margin-right: 0; border-style: outset; margin-top: 0; margin-left: 0; margin-bottom: 0 }
ul li p { margin-top: 0; margin-bottom: 0 }
ul li ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
var { font-weight: bold; font-style: italic }
table { border-color: Gray; margin-right: 7; border-style: outset; margin-top: 7; margin-left: 7; margin-bottom: 17 }
dfn { font-style: italic }
menu li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
strong { font-weight: bold }
ul { list-style-type: disc; margin-top: 10; margin-left: 50; margin-bottom: 10 }
center { text-align: center }
ul li ul { list-style-type: circle; margin-left: 25 }
kbd { font-size: small; font-family: Monospaced }
dir li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
th p { font-weight: bold; padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
ul li menu { list-style-type: circle; margin-left: 25 }
dt { margin-top: 0; margin-bottom: 0 }
ol li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
li p { margin-top: 0; margin-bottom: 0 }
strike { text-decoration: line-through }
dl { margin-top: 10; margin-left: 10; margin-bottom: 10 }
tt { font-family: Monospaced }
ul li { margin-right: 0; margin-top: 0; margin-left: 0; margin-bottom: 0 }
dir { margin-top: 10; margin-left: 40; margin-bottom: 10 }
pre p { margin-top: 0 }
th { border-color: Gray; border-style: solid; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
pre { font-family: Monospaced; margin-top: 5; margin-bottom: 5 }
td { border-color: Gray; border-style: inset; padding-left: 3; padding-bottom: 3; padding-right: 1; padding-top: 1 }
td p { padding-left: 2; padding-bottom: 3; padding-right: 2; margin-top: 0; padding-top: 3 }
code { font-size: small; font-family: Monospaced }
small { font-size: x-small }
big { font-size: x-large }
-->
</style>
</head>
<body>
<p style="margin-top: 0">
</p>
<table width="500" cellspacing="20" border="1">
<tr>
<td height="330" valign="top">
<table border="0">
<tr>
<td>
<font size="2">This is to certify that [[Client Name]], born
on [[Client Date of Birth]], of [[Client Residential
Address]], was the holder of motor vehicle driver
licence number [[Client Licence Number]], first issued on
[[First Issue Date of Holding]] and expired on [[Holding
Expiry Date]].<br></font>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table width="500" border="2">
<tr>
<td>
<table width="480" border="0">
<tr>
<td align="right">
<font size="2"><br>
<b>Fred Flintstone<br>Manager</b><br>Records Services Division<br>State
Police<br>An authorised person for the purposes of the
Road Act 1986</font>
</td>
</tr>
<tr>
<td align="left">
<font size="2"><b>User ID: wzvqv7<br>Dated: 29 November 2006</b>
</font>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>I have finally cracked it!!!!!!!!!!!!!!!!
The issue is definitely with Java Sun. "Uneven character spacing when printing JTextComponent"
It is raised on the http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6488219
And currently in OPEN state, and raised on 31 Oct 2006 and mentions it was caused by fix 4352983.
So where do we go from here. It's not good because I have tried all later version of the JVM and the issue is still there.
Why? Because it hasn't been fixed yet. Read the bug report above, as it gives more insight -- and mentions the workaround is NOT good for existing code.
So the way forward is to use an earlier version of the JVM 5.
I download the JVM version 1.5.0 (starting version) and works Ok... I would probably think version prior to 4352983 would be Ok too.
Please vote for this.... We have a workaround (use older version of the JVM).
So I am very happy. -
Print html content of an JEditorPane
Hello!
I have an JEditorPane with some HTML Content displayed (as it is displayed in a browser).
Now i want to sent this content to a printer.
After some search i found the DocumentRenderer class from this link:
http://www.fawcette.com/javapro/2002_12/online/print_kgauthier_12_10_02/
It may be trivial, but i don't know how to create a HTMLDocument Object from my JEditorPane (and its contents).
Maybe somebody can help me out with this.
my code so far:
DocumentRenderer renderer = new DocumentRenderer();
HTMLDocument doc = new HTMLDocument();
//At this point i don't know how to get my JEditorPane/it's contents "into" the HTMLDocument Object
renderer.setDocument(doc);
renderer.print(doc); Many thanks in advance for help!find it out by myself.
HTMLDocument doc = (HTMLDocument)myJEditorPane.getDocument();But now i ran in another problem:
Checkboxes are not displayed when i print this content.
Is it possible to solve this problem? -
How to set the physical font in JEditorPane with HTMLEditorKit
I am now creating a swing application which use JEditorKit to make a HMTL editor by the following code:
JEditorPane editor = new JEditorPane();
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();
editor.setEditorKit(kit);
editor.setDocument(doc);
editor.setContentType("text/html; charset="+sEncoding);
editor.getDocument();
u can see that the encoding of the html file is generated dynamically. At the same time, I also hope that the font is also set dynamically. Moreover, I don't want the font to be installed on each platform, so I am using the following code:
FileInputStream fis = new FileInputStream("Cyberbit.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fis);
Therefore, I can use this font in the Java application. However, how can I make the html file can use this font also? How can I make the HTML file to use this font in the JVM? thx!
StephenHowever, how can I make the html file can use this font also? How can I make the HTML file to use this font in the JVM? thx!This is my exact problem!
Hope you would have got the solution , could you give me some sugesstion..pls? -
Switching documents in JEditorPane
I have a program that creates an array of files and reads them one at a time to make an HTML document to display its contents. The problem I'm having is that I cannot change the contents of the document, I want the user to be able to sift through the array to view different info.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class OtherLibContact extends JScrollPane implements ActionListener
String [] command = {
"<<",
">>"
String [] headers = {
"Library Name",
"Town",
"Address",
"Librarian",
"Postal Code",
"Telephone",
"Fax",
"Email Address",
"Web Site",
"Type of Library",
"Hours"
String [] days = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
/*Variables used to list files in directory and switch between files*/
File dir;
File [] dirListed;
String [] filesListed;
String workingDir = "profiles/";
String filename = "profiles/DBprofile.dat";
/*Where the PLS record is located*/
int index = 0;
/*HTML file to be created and altered*/
String record = "current.html";
URL url;
JButton [] buttons = new JButton [command.length];
JPanel panel = new JPanel ();
JEditorPane pane = new JEditorPane ();
public OtherLibContact ()
checkDir ();
makeButtons ();
pane.setBackground (CustomColors.getAppColor ());
this.setViewportView (panel);
this.setBorder (null);
this.setBackground (CustomColors.getAppColor ());
panel.setLayout (new BorderLayout ());
panel.add ("North", buttons [0]);
panel.add ("South", buttons [1]);
panel.add ("Center", pane);
/*Makes an array out of the files found in the workingDir*/
public void checkDir ()
/*makes a new file object*/
dir = new File (workingDir);
/*only if dir is a directory does this work*/
if (dir.isDirectory ())
/*lists files in file object array*/
dirListed = dir.listFiles ();
/*creates a string array of the same size*/
filesListed = new String [dirListed.length];
/*copys the file names into the string array one by one*/
for (int i = 0; i < dirListed.length; i++)
filesListed = dirListed [i].getName ();
makeHTML (workingDir +filesListed [0]);
public void makeButtons ()
for (int i = 0; i < buttons.length; i++)
buttons [i] = new JButton (command [i]);
buttons [i].setBackground (CustomColors.getAppColor ());
buttons [i].addActionListener (this);
buttons [0].setToolTipText ("Move back one record");
buttons [1].setToolTipText ("Move forward one record");
public void setScreen ()
try
url = new URL ("file:\\\\" +ReturnInfo.getRoot ()
+record);
pane.setPage (url);
pane.setEditable (false);
catch (IOException io)
buttons [0].setText (io.toString ());
public void makeHTML (String thisfile)
String [] pr = readFile (thisfile);
int offset = 0;
/*Try to create an HTML file to display output*/
try
FileWriter fw = new FileWriter (record);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter pw = new PrintWriter (bw);
pw.println ("<HTML>");
*Makes the HTML document here
pw.println ("</HTML>");
pw.close ();
setScreen ();
catch (IOException ioe)
buttons [0].setText (ioe.toString ());
public String [] readFile (String file)
String [] fromFile = new String [38];
/*Try to read the file*/
try
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader (fr);
String line = br.readLine ();
for (int i = 0; line != null; i++)
fromFile [i] = line;
line = br.readLine ();
/*Catch errors from reading the file*/
catch (FileNotFoundException fnfe)
buttons [0].setText (fnfe.toString ());
catch (IOException ioe)
buttons [0].setText (ioe.toString ());
return fromFile;
public void actionPerformed (ActionEvent ae)
Object source = ae.getSource ();
/*'workingDir' +'filesListed' = path to files*/
if (source == buttons [0])/*BACK*/
File theHTML = new File (record);
if (theHTML.isFile ())
theHTML.delete();
makeHTML (workingDir +filesListed [0]);
else
makeHTML (workingDir +filesListed [0]);
else /*NEXT*/
File theHTML = new File (record);
if (theHTML.isFile ())
theHTML.delete();
makeHTML (workingDir +filesListed [1]);
else
makeHTML (workingDir +filesListed [1]);
I have a different app where I use the button to refresh to contents of the HTML page after a search has been performed. I thought if I could pass a new file to it every time I could refresh the page with different content. Any and all help is apprecaited
-conor.You can use HTMLEditorKit for this purpose.
use method createDefaultDocument() to create blank document.
after that use method
read(Reader in,Document doc,int pos);
to read content of HTML file in the Document.
and when you create list of required document just change content of JEditorPane using setDocument(Document doc); method
best regards
Stas -
I'm trying to display html pages inside of a JEditorPane using a CSS. I've got some lines of code but I'm not sure which are needed. Here's what I have.
htmlPane.setEditable(false);
htmlPane.setContentType("text/html");
HTMLEditorKit kit = new HTMLEditorKit();
kit.setStyleSheet(getStyles());
HTMLDocument htmlDoc = (HTMLDocument)kit.createDefaultDocument();
htmlPane.setEditorKit(kit);
htmlPane.setDocument(htmlDoc);
getStyles() points to my .css file.
Now how do I display the page? Do I use htmlPane.setPage(), setText(), read(), or something else? If i'm supposed to use htmlDoc how do I add content to that?
I need to display an xml file formatted nicely without the tags. Any help or advice would be greatly appreciated.
ThanksHi Elad,
For JSPs to access this css file here is the sample code. Make sure that you keep your css file inside dist->css folder.
<Html>
<Head>
<%@ page import="com.sapportals.portal.prt.component.IPortalComponentResponse"%>
<%@ page import="com.sapportals.portal.prt.resource.IResource"%>
<%
IPortalComponentResponse componentResponse =
(IPortalComponentResponse)pageContext.getAttribute(javax.servlet.jsp.PageContext.RESPONSE);
IResource suckerfishCss = componentRequest.getResource(IResource.CSS, "css/GlobalReportStyles.css");
componentResponse.include(componentRequest, suckerfishCss);
%>
</Head>
<body>
</body>
</html>
Now the class files must be availble to you.
Regards,
Vishal -
Hi all ,
I have a problem with JEditorPane, I would split it in pages .
I mean , i load a StyledDocument from a file and I would show only a page a time, I tried a copy and paste tecnique .
the whole file is in a JEditorPane and the single page is copied in another JEP that is showed.
this is the code :
public void split(JTextPane from, JTextPane to,int fromWhere ,int toWhere,int jepFromWhere){
from.select(fromWhere,fromWhere+toWhere);
from.copy();
to.setCaretPosition(jepFromWhere);
to.paste();
public void setDoc(DefaultStyledDocument document){
this.doc = document;
jep.setVisible(false);
textPaneAppoggio.setDocument(document);
stateChanged=false;
stop = true;
while( how < doc.getLength() && howmuch >0){
split(textPaneAppoggio,jep,how,howmuch,jepHow);
if (stateChanged){
stateChanged = false;
}else{
how = how+howmuch;
jepHow = jepHow+howmuch;
stop = false;
jep.setVisible(true);
return ;
public void adjustmentValueChanged(AdjustmentEvent e) {
if(!stateChanged && stop){
jep.setCaretPosition(jep.getDocument().getLength());
if (e.getValue()!=0){
howmuch = 0;
jep.select( how , jep.getCaretPosition() - e.getValue());
jep.cut();
return ;
jep.select( how , jep.getCaretPosition() - e.getValue());
jep.cut();
howmuch = howmuch /2;
stateChanged = true;
thanks for the replies !!!the error is that sometimes the doc setting isn't stopped so the scrolling is done.
I tried the set AutoScroll feature but nothing different appened the JScrollPane scrolls anyway -
HELP!!! character display problem in JEditorPane
hi,
I got a headache with my program which needs to display multiple language html page in a JEditorPane. For example, if user requests a Chinese page then page is read in from an inputstreamreader using Chinese charset encoding. But what JEditorPane displays is squares and this is a very common font problem. I did everything I can
copy font.properties.zh to font.properties
set JEditorPane font as Font("SIMSUN",Font.PLAIN,12)
with the bug unsolved so far.
I am using Windows 2000/ME in UK locale.
Anybody could help please???yes, the input data, for example in the case of Chinese Simpilify Character, is read in using a decoder with charset GB2312. I think I can print them out on prompt console but in a unrecognizable format.
Anyway, I would like to reconfirm the steps I took: (Presumably I know I am going to load a Chinese page)
1. rename font.properties.zh to font.properties
2. set the font of JEditorPane as ("SIMSUN",Font.PLAIN,12)
3. when try to load a Chinese page, there should be a ChangedCharSetException. extract the charset from the exception and use it to construct a new InputStreamReader.
4. I also set the content-type of JEditorPane as something like "text/html; charset=gb2312"
5. read in the data and parse it into a HTMLDocument instance.
6. finally use setDocument method to display the document on the JEditorPane.
In this way, the page gets displayed in unknown characters.
Anybody could show me something different but feasiable? Please!!! -
Is there a way to cache documents in JEditorPane ?
I am using a JEditorPane to load html pages.
some of my pages are quite big and take some time to load. I would like to cache the pages so the next time the user loads a cached page, the page will load very quickly.
It seems that what I need to cache is the html document that represents the model. However using JEditorPane setDocument( ) method with the cached document takes the same time as loading a new page.
so perhaps i need to cache the views also ?
thanks.1. I load documents only from the local drive.
2. The pages I load can be quite big.
3. I load the pages synchronically
I have measured a bit of times for loading a big page.
when the page is new it takes 11 seconds to build the document. with a cached document it takes about 7 seconds.
the painting of the views takes little time.
my question is: if I supply the editor pane with a fully built document model, why does it still take him 7 seconds to ready it?
or if someone knows a way to load a cached document instead of using the setDocument( ) method.
Thanks -
Exception is thrown when using JEditorPane to display html
Hello,
I have this basic browser to display some pages from our intranet. Here's the code for it:
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
public class BrowserPanel extends JPanel {
private JEditorPane pane = null;
// Constructors
public BrowserPanel() {
pane = new JEditorPane();
pane.setEditable(false);
JScrollPane sp = new JScrollPane(pane);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(sp, BorderLayout.CENTER);
// Methods
public void setContent(String str) {
StringBuffer sb = new StringBuffer(500);
sb.append("http://local.com/cgi-bin/search.pl?arg=");
sb.append(str);
try {
URL url = new URL(sb.toString());
pane.setPage(url);
} catch (MalformedURLException e) {
System.err.println("Malformed URL: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
On some of the pages I get text all scrambled and the following exception comes up:
java.lang.ArrayIndexOutOfBoundsException
at javax.swing.text.html.TableView$RowView.layoutMajorAxis(TableView.java:1393)
at javax.swing.text.BoxView.layout(BoxView.java:580)
at javax.swing.text.BoxView.setSize(BoxView.java:265)
at javax.swing.text.BoxView.paint(BoxView.java:283)
at javax.swing.text.html.TableView$RowView.paint(TableView.java:1315)
at javax.swing.text.html.TableView.paint(TableView.java:740)
at javax.swing.text.BoxView.paintChild(BoxView.java:104)
at javax.swing.text.BoxView.paint(BoxView.java:294)
at javax.swing.text.html.BlockView.paint(BlockView.java:240)
at javax.swing.text.BoxView.paintChild(BoxView.java:104)
at javax.swing.text.BoxView.paint(BoxView.java:294)
at javax.swing.text.html.BlockView.paint(BlockView.java:240)
at javax.swing.plaf.basic.BasicTextUI$RootView.paint(BasicTextUI.java:1170)
at javax.swing.plaf.basic.BasicTextUI.paintSafely(BasicTextUI.java:523)
at javax.swing.plaf.basic.BasicTextUI.paint(BasicTextUI.java:657)
at javax.swing.plaf.basic.BasicTextUI.update(BasicTextUI.java:636)
at javax.swing.JComponent.paintComponent(JComponent.java:395)
at javax.swing.JComponent.paint(JComponent.java:687)
at javax.swing.JComponent.paintChildren(JComponent.java:498)
at javax.swing.JComponent.paint(JComponent.java:696)
at javax.swing.JViewport.paint(JViewport.java:668)
at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
Many thanks for any clues on how to make it work.
cheers,
--JavanTyou should specify that this is an HTML veiwer explicitly, by writting something similar to this,
editor.setContentType("text/html");
kit = (HTMLEditorKit) editor.getEditorKit();
editor.setEditorKit(kit);
doc = (HTMLDocument) kit.createDefaultDocument();
editor.setDocument(doc); -
Inserting any JComponent in a JEditorPane
Hi, I'm having some trouble using JEditorPane and JTextPane. I would like to include some JComponent of my own into them.
With JTextPane, no problem, let's create a style with
StyleConstants.setComponent(myStyle, myComponent);
then insert a space char in the Document using this style. Good.
Problem comes when I want to insert my components into an HTML document, using JEditorPane. This method raises no runtime problem but does nothing visible. Why ? Even more surprising, if I force the JEditorPane to a simple DefaultStyledDocument
JEditorPane editorPane = new JTextPane();
editorPane.setDocument(new DefaultStyledDocument());
it doesn't work better. In such a case, ain't we in exactly the same configuration than with JTextPane ? BTW, why is JTextPane derived from JEditorPane if we cannot retreive parent's behaviour (HTML or RTF rendering) in the child class ?
Yes, I'm confused...
If your mind is clearer than mine on those topic, could you give me a piece of advice, or a link to a solution or an exemple on all of this ? Thanks,
MatthieuNo idea anybody on how I could insert JComponents of my own in a JEditorPane ?
Why the simple Document.insertString () don't work in a JEditorPane if the style is not HTML ?
Is it possible to tweak JTextPane to make it render HTML (using a Kit) then insert my own styles in it ?
Thx.
Matthieu -
URGENT: JEditorPane (a Java Browser) displaying HTML form
Hi,
I am using JEditorPane to display the wb pages but geeting problem as
I don't get any kind of event when I click on the HTML form SUBMIT button though it does work but didn't allow me to get the URL of the new page that I got after hitting this SUBMIT button..
I searched the whole net and it seems to me that lot of people got this problem...
As I need this for my project please HELP me as soon as possible.This may be too late for you (hopefully not), but I had the same problem a little while ago and just figured out how to fix it. Basically, you need to examine the Element structure of the html yourself and manually handle the form, as far as I can tell. There are several ways to display a URL in a JEditorPane, but the most straight-forward (JEditorPane.setPage(URL url)) doesn't actually store the Element structure anywhere accessible. Here's the code to load the page:
JEditorPane contents;
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument htmlDoc = new HTMLDocument();
contents.setEditorKit(kit);
contents.setDocument(htmlDoc);
URL url = new URL("http://blahblahblah.com");
contents.read(url.openStream(), htmlDoc);Now that you have the page loaded correctly, you can access to the Elements within. You can use htmlDoc.getDefaultRootElement() to get the root and then iterate recursively through all the child Elements, checking out the Attributes of each. This will look for the submit button and add a listener to it for you:
private void parseElements(Element elem) {
AttributeSet atts = elem.getAttributes();
//If this is the submit button, add a listener:
Object model = atts.getAttribute(StyleConstants.ModelAttribute);
Object type = atts.getAttribute(HTML.Attribute.TYPE);
if ((type != null) && (type.equals("submit"))) {
DefaultButtonModel btn = (DefaultButtonModel) model;
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("Yay!");
//Recurse
for (int i = 0; i < elem.getElementCount(); i++)
parseElements(elem.getElement(i));
}Of course, printing out "Yay!" is not really very helpful. When you're parsing through the Elements, check for the attribute StyleContsants.ModelAttribute. If that exists, you can cast it to the correct type of Model (see the documentation for HTMLDocument.HTMLReader.FormAction for information about what types of models to expect from what types of HTML elements) and store it until the "submit" button is pressed. Then all you have to do is get all the data from the models, format it and submit it to the action URL in either a "get" or a "post." The action URL is stored, in Java 1.3, in the HTML.Tag.Form attribute of one of the Elements (I don't remember which one). Getting that attribute returns a SimpleAttributeSet, and you get the HTML.Attribute.Action out of that. In Java 1.4 it's easier to find, you just have to look for the HTML.Attribure.Action attribute in one of the Elements.
Why isn't this all automatically done for you? I don't know. Good luck.
-Nathan -
How can I split long words to feet the line in JEditorPane
Hi,
Can someone help me ?
I'm trying to write long words in JEditorPane,
and I want the JEditorPane to split them, so it will feet the line...
(something like word wrapping in JTExtArea).
How can I fix my code so it will work?
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
public class Testing extends JFrame {
public Testing() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-210)/2, (screenSize.height-200)/2, 210, 200);
editorPane = new JEditorPane();
HTMLEditorKit kit = new HTMLEditorKit();
editorPane.setEditorKit( kit );
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
editorPane.setDocument( doc );
editorPane.setEditable(false); // or true
String htmlText =
"<html>"
+"<body>"
+"How can I use word wrapping with html JEditorPane?"
+"<br>How can I split the next long word, so it will feet the line?"
+"<br>loooooooooooooooooooooooooooooooooooooooong"
+"</body>"
+"</html>";
try {
kit.insertHTML(doc, editorPane.getCaretPosition(), htmlText.substring(6) + "<br>", 0, 0, HTML.Tag.HTML);
catch( Exception exp ) {
exp.printStackTrace();
getContentPane().add(editorPane, BorderLayout.CENTER);
public static void main(String args[]) {
new Testing().setVisible(true);
private JEditorPane editorPane;
}Thanks,
MaozSorry forget about paragraph view.
Here the new code.
regards,
Stas
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
import javax.swing.text.*;
public class Test extends JFrame
public Test()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-210)/2, (screenSize.height-200)/2, 210, 200);
editorPane = new JEditorPane();
MyHTMLEditorKit kit = new MyHTMLEditorKit();
editorPane.setEditorKit( kit );
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
editorPane.setDocument( doc );
// editorPane.setEditable(false); // or true
String htmlText =
"<html>"
+"<body>"
+"<br>How can I split the next long word, so it will feet the line?"
+"<br>loooooooooooooooooooooooooooooooooooooooong"
+"</body>"
+"</html>";
try
kit.insertHTML(doc, editorPane.getCaretPosition(), htmlText.substring(6) + "<br>", 0, 0, HTML.Tag.HTML);
catch( Exception exp )
exp.printStackTrace();
getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
public static void main(String args[])
new Test().setVisible(true);
private JEditorPane editorPane;
class MyHTMLEditorKit extends HTMLEditorKit
private static final ViewFactory defaultFactory = new MyViewFactory ();
public ViewFactory getViewFactory()
return defaultFactory;
static class MyViewFactory extends HTMLFactory
public View create(Element elem)
View v=super.create(elem);
if (v instanceof InlineView )
return new LabelView(elem);
else if (v instanceof javax.swing.text.html.ParagraphView) {
return new MyParagraphView(elem);
return v;
static class MyParagraphView extends javax.swing.text.html.ParagraphView {
public MyParagraphView(Element elem) {
super(elem);
protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
if (r == null) {
r = new SizeRequirements();
float pref = layoutPool.getPreferredSpan(axis);
float min = layoutPool.getMinimumSpan(axis);
// Don't include insets, Box.getXXXSpan will include them.
r.minimum = (int)min;
r.preferred = Math.max(r.minimum, (int) pref);
r.maximum = Short.MAX_VALUE;
r.alignment = 0.5f;
return r;
} -
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 -
Apply formatting in a JEditorPane and export the content in HTML.
Hi,
I'm writing, a program to allow the user to enter a formated text and even add images in a JEditorPane.
Here is a simple sample of the code:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*; //for layout managers and more
import java.awt.event.*; //for action events
import java.net.URL;
import java.io.IOException;
public class EditorPane extends JPanel{
private String newline = "\n";
private JPanel buttonPanel;
private JPanel textPanePanel;
private JEditorPane myEditorPane;
private JButton boldButton;
private JButton colorButton;
private JButton imgButton;
private JButton saveButton;
public EditorPane() {
createGUI();
private void createGUI() {
buttonPanel = new JPanel();
boldButton = new JButton("Bold");
boldButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
boldButtonActionPerformed(evt);
colorButton = new JButton("Color");
colorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
colorButtonActionPerformed(evt);
imgButton = new JButton("Image");
imgButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
imgButtonActionPerformed(evt);
saveButton = new JButton("Save");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
buttonPanel.setLayout(new GridLayout(1, 4));
buttonPanel.add(boldButton);
buttonPanel.add(colorButton);
buttonPanel.add(imgButton);
buttonPanel.add(saveButton);
textPanePanel = new JPanel();
textPanePanel.setLayout(new BorderLayout());
myEditorPane = this.createEditorPane();
JScrollPane paneScrollPane = new JScrollPane(myEditorPane);
textPanePanel.add(paneScrollPane, BorderLayout.CENTER);
this.setLayout(new BorderLayout());
this.add(buttonPanel, BorderLayout.NORTH);
this.add(textPanePanel, BorderLayout.CENTER);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("TextSamplerDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EditorPane newContentPane = new EditorPane();
//newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setSize(300,300);
frame.setVisible(true);
private JEditorPane createEditorPane() {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(true);
java.net.URL helpURL = TextSamplerDemo.class.getResource(
"simpleHTMLPage.html");
if (helpURL != null) {
try {
editorPane.setPage(helpURL);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + helpURL);
} else {
System.err.println("Couldn't find file: simpleHTMLPage.html");
return editorPane;
private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("boldButtonNextActionPerformed");
//myEditorPane
// TODO add your handling code here:
private void colorButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("colorButtonActionPerformed");
// TODO add your handling code here:
private void imgButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("imgButtonActionPerformed");
// TODO add your handling code here:
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("saveButtonActionPerformed");
String newStr = new String("this is the new String");
//newStr.setFont(new java.awt.Font("Tahoma", 0, 14));
this.myEditorPane.replaceSelection("sdfsdfsd");
// TODO add your handling code here:
}and the HTML Code of simpleHTMLPage.html is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<p>Simple text</p>
<p><strong>Bold text</strong></p>
<p><em>Italic text</em></p>
<p align="center">Center text</p>
<p><font color="#000099"><strong>Color text</strong></font></p>
<p>image here : <img src="images/Pig.gif" width="121" height="129"></p>
<p> </p>
</body>
</html>By pressing the Save button I can change the selected text.
I don�t know the way to get and apply the format (size, color �) to only the selected text and display the selected image in real time in the EditorPane. Like if you press the Bold button, the selected text font will be change to bold.
I would like to get or save the HTML code of the content of the EditorPane by pressing the Save button, How to make it?
I can apply the formatting on the selected text in a JTextPane, but I don't know the way to save or export the content in HTML. By doing that it could fix my problem too.
So any help to do that will be much appreciated.
Thanks.Hi,
Tks for your answer. That one I can do it. I would like to display the selected text in bold instead of adding the tag in the JEditorPane. If I get you right, you get the hole content of the JEditorPane and save it. How did you get it ? And before saving that in the database, did you fing the keysWord to convert the HTML tag in the corresponding entities ?
Bellow you have a sample of code to make the formatting in the JTextPane.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.text.Highlighter;
import javax.swing.event.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.text.BadLocationException;
public class MonJTextPane extends JFrame implements CaretListener, ActionListener
* Attributs :
private JTextPane monTextPane;
private JLabel monLabel;
private JButton monBouton;
private StyleAide style; // class qui defini les effets de style de l'editeur
* Constructeur :
public MonJTextPane ()
{ super ("Aide");
// construction du composant Texte
this.style = new StyleAide (new StyleContext ());
this.monTextPane = new JTextPane ();
this.monTextPane.setDocument (style);
this.monTextPane.addCaretListener (this);
// construction de la fenetre :
this.getContentPane ().setLayout (new BorderLayout ());
this.setBounds (150,150,600,550);
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
this.monLabel = new JLabel ("Auncune ligne saisie...");
this.monBouton = new JButton ("change de style");
this.monBouton.addActionListener (this);
JPanel panel = new JPanel ();
panel.setLayout (new GridLayout (1,2));
panel.add (monLabel);
panel.add (monBouton);
this.getContentPane ().add (panel, BorderLayout.SOUTH);
this.getContentPane ().add (this.monTextPane, BorderLayout.CENTER);
this.setVisible (true);
* Methodes :
private int getCurrentLigne ()
{ return ( this.style.getNumLigne (monTextPane.getCaretPosition ())+1 );
public int getCurrentColonne ()
{ return ( this.style.getNumColonne (monTextPane.getCaretPosition ())+1 );
* Methodes CaretListener:
// ecoute les deplacements du curseur d'insertion
public void caretUpdate(CaretEvent e)
{ int debut = java.lang.Math.min (e.getDot (), e.getMark ());
int fin = java.lang.Math.max (e.getDot (), e.getMark ());
this.monLabel.setText ("Ligne numero : "+ this.getCurrentLigne ()+" Colonne : "+this.getCurrentColonne ()+" (debut : "+debut+", fin : "+fin+")");
* Methodes ActionListener:
public void actionPerformed (ActionEvent e)
{ int start = monTextPane.getSelectionStart();
int end = monTextPane.getSelectionEnd();
int debut = java.lang.Math.min (start, end);
int fin = java.lang.Math.max (start, end);
int longueur= fin - debut;
this.style.changeStyleSurligne (debut, longueur);
// lance le tout ....
public static void main (String argv [])
{ new MonJTextPane ();
// la Classe DefaultStyledDocument correspond a la classe utilise comme Model pour les
// composant Texte evolue comme : JTextPane ou JEditorPane
// en derivant de cette derniere nous pouvons donc redefinir les methodes d'insertion afin de personnalise
// le style d'ecriture en fonction du texte et creer une methode permettant de modifier le style utilise pour
// une partie de texte deja ecrite.
class StyleAide extends DefaultStyledDocument
* Constructeur :
public StyleAide (StyleContext styles)
{ super (styles);
initStyle (styles);
* Methodes :
// redefini pour choisir l'effet de style a utiliser
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{ try
{ // si le texte insere est egale a HELP le texte s'ecrit avec le style "styleOp"
if ( str.equals ("HELP") )
{ super.insertString (offs, str, getStyle ("styleOp"));
else // sinon le texte est ecrit avec le style "styleNormal"
{ super.insertString (offs, str, getStyle ("styleNormal"));
catch (BadLocationException e)
{ System.out.println ("Tuuuttt erreur Insere");
// modifie le style d'ecriture d'un texte deja ecrit compris
public void changeStyleSurligne (int positionDepart, int longueur)
{ setCharacterAttributes (positionDepart, longueur, getStyle ("styleKeyWord"), true);
// le Model d'un composant texte est enregistre sous form d'un arbre
// cette methode permet de recuperer le noeud root de l'arbre
private Element getRootElement ()
{ return this.getDefaultRootElement ();
// methode permettant d'obtenir la ligne correspondant a un offset donnee
public int getNumLigne (int offset)
{ Element eltR = getRootElement ();
int numLigne = eltR.getElementIndex (offset);
Element elt = eltR.getElement (numLigne);
if ( offset != elt.getEndOffset () )
{ return numLigne;
else
{ if ( numLigne != 0 )
{ return numLigne+1;
return 0;
public int getNumColonne (int offset)
{ Element eltR = getRootElement ();
Element elt = eltR.getElement (eltR.getElementIndex (offset));
int numColonne = offset-elt.getStartOffset ();
return numColonne;
// Defini les differents styles
private static void initStyle (StyleContext styles)
{ // definition du style pour le texte normal (brute)
javax.swing.text.Style defaut = styles.getStyle (StyleContext.DEFAULT_STYLE);
javax.swing.text.Style styleNormal = styles.addStyle("styleNormal", defaut);
StyleConstants.setFontFamily (styleNormal, "Courier");
StyleConstants.setFontSize (styleNormal, 11);
StyleConstants.setForeground(styleNormal, Color.black);
javax.swing.text.Style tmp = styles.addStyle("styleKeyWord", styleNormal);
// Ajout de la couleur blue et du style gras pour les mots cle
StyleConstants.setForeground(tmp, Color.blue);
StyleConstants.setBold(tmp, true);
tmp = styles.addStyle("styleOp", styleNormal);
// Ajout de la couleur rouge pour le style des operateurs
StyleConstants.setForeground(tmp, Color.red);
}But it hard for me to convert it in the corresponding HTML document.
Did you have and idea
Tkks
Maybe you are looking for
-
Greater Than Function in Script Logic File
BPC Experts, I've got a pretty simple script logic file to calculate salary amounts, overtime, etc. The purpose of this logic is for forecasting. I have two referenced dimensions, TIME and SCENARIO, where TIME.MONTHNUM is equal to its relative mont
-
What's the solution about data persistence in BPM?
In some cases,data of completed processes need to be stored and reused in some applications.But in current BPM,I can't find where the data is stored and applications can't find interfaces to acquire these data.For example,if I want to check last mont
-
Why is my itunes account disabled? I corrected my payment information.
-
DBMS_SESSION.RESET_PACKAGE
Hi Guru's, I was using DBMS_SESSION.RESET_PACKAGE in oracle version 9.2.0.6.0.It was working fine.But when that application is tested in after apply patch 9.2.0.8.0, its showing different face.All the global variables are cleared from the memory only
-
Dark webcam when using the MSN on Satellite Pro notebook
Guys ... My built in cam in my Satellite Pro laptop seems working fine when I open it .. But when I use it with MSN Messenger its always dark... I mean if I set it on night mood it would work with the cam software but not with MSN. What should i do !