JEditorPane & Wordwrap

Hi!
I have been spending loads of time on google trying to find an answer to this problem. I have not been able to solve this by my own so now I turn to the forums-.-
I am using a JEditorPane to display text using HTML. I create my JEditorPane like this:
public class ClassName extends JPanel {
    public JEditorPane a;
    public MyEditorPane(String contents) {
        super(new GridLayout());
        a = new JEditorPane("text/html", contents);
        JScrollPane scrollingArea = new JScrollPane(a);
        add(scrollingArea, BorderLayout.CENTER);
}I have seen word wrap working on JTextArea. Is there something similar that works for an editor pane? if not, HTML has a word wrap of its own. Is it possible to manage word wrap using any of these methods?
Thanks in advance

It works fine for me, word wrapping is the default behaviour.
super(new GridLayout());
add(scrollingArea, BorderLayout.CENTER);Using a BorderLayout constraint on GridLayout doesn't make sense (although it shouldn't cause a problem either). Since you don't understand the basics of using layout managers I can only guess you might have a problem somewhere else in your code. Read the section from the Swing tutorial on "Using Layout Managers".
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://sscce.org], that demonstrates the incorrect behaviour.

Similar Messages

  • Wordwrap nodes in jtree

    Anyone know how we can do wordwrap of nodes in jtree?
    Please help...
    Thanks.

    Any example on this? what html code should I use? The simplest possible, eg
    yourNode.setText("<html>" + yourNodeText + "</html>");Most JComponents can render this html string and produce a good result. But if you wanna get a little more complex and use styles and other web things, then do as said, (two posts above) and use a JEditorPane specifically for cell renderer
    ICE

  • Repaint a JEditorPane after inserting data in the Document

    Hi,
    I have a button that inserts some text in a Document using the method insert(int offset, ElementSpec[] data)After that insert, the View recalculates the heights of the text lines, but they don't get refreshed on the JEditorPane. I have to manually insert a new line to make the JEditorPane get updated with the new line height.
    I have tried using invalidate() and repaint() but nothing happens. Is there another way to refresh the contents of the JEditorPane?
    Thanks!!

    revalidate() didn't work. I still have to press "enter" in any part of the document in order to have the line height changed. The method that recalculates the height of the line is View.getPreferredSpan(int) but it isn't called until I insert a new line by pressing enter.
    I think now it's not a repainting issue, I move the window outside the screen and back again and it still doesn't update. The problem is that getPreferredSpan() is not called when it repaints.
    Thanks for your response. I will try to find out how to have the view's size recalculated when I insert content.

  • How to insert hyperlinks in RTF document shown in JEditorPane?

    This is a compound question so bear with me on this one :)
    What I need is to insert an hyperlink in a JEditorPane; Store it as RTF code; Retrieve it; Show it and click on it to go the the destination.
    1) So, first question, is there some method to automatically add the hyperlink and will it be saved in RTF with RTFEditorKit? (I'm actually using AdvancedRTFEditorKit but an answer to either will be enough)
    2) I tried a method that adds what appears as a link but the document that is stored doesn't have the necessary RTF codes, only the formatting that makes it look like a link. I also checked the actual RTF codes I'd need to add and they seem easy to do. So, is there a way to add the actual underlying RTF codes to the document while it's in the JEditorPane?
    I know the question(s) isn't too specific, if you can shed some light over the whole thing and point me in the right direction, it'd be great!

    Just a follow up to my own question. I found a way to answer my question 2) and I'm now storing the rtf code for hyperlinks. Now, when I show the document in JEditorPane with RTFEditorKit, I get the name of the hyperlink with no formatting indicating that it's a hyperlink.
    Example. The link "http://www.google.com" with the name "Google", only shows "Google" in plain text.
    Is it because the components I'm using don't support hyperlinks from RTF files even though they're supported from HTML files?
    Is there any way you can see this working? Is it possible to include something inside the JEditorPane that the user can click, instead of the hyperlink?

  • HTML file is not being shown properly in the JEditorPane

    Hi,
    I am using JEditorPane to display an HTML file from the local disk. This HTML file contains the html tables. Now when this file is getting displayed in the JEditorPane, one top row grid is not being displayed in the editor pane. content of the row is there...but the column grid is missing. All other rows and columns are being shown but the first row-column grid which contains the heading for column.
    Also when I m printing the content of this JEditorPane using Java Print API then no grid is being printed on the paper. content is coming properly but no table grids. when i have taken the print out of the original html file from the browser then table grids are being printed out properly.
    Please do help me out in showing the HTML file in the JEditorPane properly and printing the same.
    Many Thanks,
    gshankar

    Hi,
    JEditorPane renders HTML with many limitations.
    You can use JDIC for the same. refer: jdic.dev.java.net
    But JDIC does not work on windows 98.
    Anand

  • Highlighting text in JEditorPane using HTMLEditorPane

    I am using JEditorPane extending HTMLEditorkit. In the HTMLEditorkit when we use the span tag for highlighting the text of a line, it is just not showing it. It starts the color and ends it there and then. It looks like a small dot and doesnot spans the whole line.
    Is this a bug or something in JAVA 1.3.1. If anyone of you knows how to do it please let me know.
    I need it for a project which has a deadline.
    Thanks.

    JEditorPane is not rendering and HTMLDocument.HTMLReader is not reading the SPAN tag. In other words, the SPAN tag is not supported in Java. You can still use it by overriding the mentioned classes. My application SimplyHTML gives an example of how this can be done. Please visit http://www.lightdev.com/dev/sh.htm
    Ulrich

  • How to modify text insertion position in HTML in a JEditorPane

    Hi all,
    Thanks in advance if anyone knows the type of code I need to look at to solve my problem.
    It involves the insertion point (in the actual HTML) when editing text in a JEditorPane using type html/txt.
    for example, lets say you start to add text by typing in a JEditorPane which already contains some text.
    The html is:
    <html><head></head>
    <body>
    <span>inside</span>
    </body>
    </html>
    which represents visually:
    inside
    The user places the caret (by pointing and clicking the mouse) after the word 'inside'.
    The user types the word 'outside'.
    The resulting html will look like this:
    <html><head></head>
    <body>
    <span>insideoutside</span>
    </body>
    </html>
    I would very much prefer it to look like this:
    <html><head></head>
    <body>
    <span>inside</span>outside
    </body>
    </html>
    Does anyone know how to influence the position of insertion in this way?
    Thanks again,
    sean

    Success!!!
    In a tiny bit of a hacky way.
    I will share my path to success. Though I am sure it could be improved. The solution (except for the minor hack to get it to work at all) is quite simple.
    And it did indeed involve the use of the DocumentFilter.
    So, to recap, My objective was to prevent the user from causing the addition of text within a certain span tag in my HTML when editing visual through a JEditorPane.
    Specifically, in my HTML I have a number of span tags identified through a type attribute. My span tags look like this:
    <span type="reserved">hello</span>
    I wanted to prevent the user from being able to type (visually) to cause either this:
    <span type="reserved">next text hello</span>
    or
    <span type="reserved">hello new text</span>
    or
    <span type="reserved">he new text llo</span>
    Initially, I had used a Caret listener, and moved the caret along, which, besides being hugely ugly, wouldn't fix the main problem of, even when the user starts typing after the word 'hello' on the visual pane, the text would be appended within the span tag, and not outside. Even though if I were to check my position (with the following code) I would be told it wasn't associated with the span attribute at all
              Element elem = hdoc.getCharacterElement(pos);
              AttributeSet a = elem.getAttributes();
              AttributeSet spanAttributeSet = (AttributeSet)a.getAttribute(HTML.Tag.SPAN);
              // if spanAttributeSet is not null, then we properly found ' a span '.
              // now we need to discover if it is one of OUR spans
              if (spanAttributeSet != null)
                    { // blah .... do something
                    }Regardless of what it told me with the above code, if i were to type in at that position (just after the hello) it would be added to the span tag. Which is what I didn't want.
    But the discovery of the DocumentFilter was what I needed to look at. Although, I had a very strange problem of having to reassign the document filter several times to the editorPane (later checks would see it as null). I don't know why I have this problem, but I have made a work-around by ensuring the DocumentFilter is still assigned by reassigning it every time the user moves the caret in the editorpane. Not nice, but prevents my filter from being ignored.
    The real solution:
    Using the DocumentFilter, I was able to solve both my problems of , not allowing the user to type inside the word 'hello', and preventing the text typed after the 'hello' being appended inside the span tag by the Document model.
    This is my code:
               myFilter = new DocumentFilter(){
                    public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attrs) throws BadLocationException
                         System.out.println("in insert string");
                           if (isCaretOnReservedObject((HTMLDocument)fb.getDocument(), offset))
                                throw new BadLocationException("Reserved position", offset);
                           else
                                    Object val = attrs.getAttribute(HTML.Attribute.TYPE);
                                if (val!=null && val.equals("reserved"))
                                     super.insertString(fb, offset, string, null);
                                else
                                     super.insertString(fb, offset, string, attrs);
                    @Override
                    public void remove(DocumentFilter.FilterBypass fb,
                            int offset,
                            int length)
                     throws BadLocationException
                         super.remove(fb, offset, length);
                      public void replace(DocumentFilter.FilterBypass fb,
                             int offset,
                             int length,
                             String text,
                             AttributeSet attrs)
                      throws BadLocationException
                           if (isCaretOnReservedObject((HTMLDocument)fb.getDocument(), offset))
                                throw new BadLocationException("Reserved position", offset);
                           else
                                    Object val = attrs.getAttribute(HTML.Attribute.TYPE);
                                if (val!=null && val.equals("reserved"))
                                     super.replace(fb, offset, length, text, null);
                                else
                                     super.replace(fb, offset, length, text, attrs);
               ((AbstractDocument)this.getInternalJEditorPane().getDocument()).setDocumentFilter(myFilter);
         protected boolean isCaretOnReservedObject(HTMLDocument hdoc, int pos)
              boolean retval = false;
              Element elem = hdoc.getCharacterElement(pos);
              AttributeSet a = elem.getAttributes();
              AttributeSet spanAttributeSet = (AttributeSet)a.getAttribute(HTML.Tag.SPAN);
              // if spanAttributeSet is not null, then we properly found ' a span '.
              // now we need to discover if it is one of OUR spans
              if (spanAttributeSet != null)
                   Object type = spanAttributeSet.getAttribute(HTML.Attribute.TYPE);
                   if (type != null && type.equals("reserved"))
                        // for our logging, we get the ref, which holds the source
                        // of our value later
                        System.out.println(elem + ": the value is: " + spanAttributeSet.getAttribute("ref"));
                        retval = true;
              return retval;
         }And now, when I attempt to type on the word 'hello', nothing happens (great!), and when I type after it, it is not assigned the span tag attribute, and we later find it (when outputting html) at the outside of the span tag.
    I don't know if there is a better way to do this, but it looks and works fairly cleanly so far.
    And thanks to stas for your reply...... Maybe this is what you meant. . it certainly was the attributes I needed to fiddle with here, and it gave me an extra hint of what to look for when researching the problem.
    Edited by: svaens on Sep 28, 2009 6:56 PM
    forgot to add dependency to code snippet
    Edited by: svaens on Sep 28, 2009 9:34 PM
    fix bug

  • How can an applet retrieve the values of a HTML form shown in a JEditorPane

    Hi,
    I'm doing an applet that contains a JTree and a JEditorPane
    among other components. Each node of the JTree represents some
    information that is stored in a database, and whenever a JTree
    node is selected, this information is recovered and shown in
    the JEditorPane with a html form. To make the html form,
    the applet calls a servlet, which retrieves the information of
    the node selected from the database. This information is stored
    like a XML string, and using XSLT, the servlet sends the html
    form to the applet, which shows it in the JEditorPane.
    My problem is that I don't know how I can recover new values
    that a user of the application can introduce in the input fields
    of the html form. I need to recover this new values and send them
    to another servlet which store the information in the database.
    If someone could help me I'd be very pleased.
    Eduardo

    At least I found a fantastic example. Here it is:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    public class FormSubmission extends JApplet {
    private final static String FORM_TEXT = "<html><head></head><body><h1>Formulario</h1>"
    + "<form action=\"\" method=\"get\"><table><tr><td>Nombre:</td>"
    + "<td><input name=\"Nombre\" type=\"text\" value=\"James T.\"></td>"
    + "</tr><tr><td>Apellido:</td>"
    + "<td><input name=\"Apellido\" type=\"text\" value=\"Kirk\"></td>"
    + "</tr><tr><td>Cargo:</td>"
    + "<td><select name=\"Cargo\"><option>Captain<option>Comandante<option>General</select></td>"
    + "</tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" value=\"Enviar\"></td>"
    + "</tr></table></form></body></html>";
    protected HashMap radioGroups = new HashMap();
    private Vector v = new Vector();
    public FormSubmission() {
    getContentPane().setLayout(new BorderLayout());
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    editorPane.setEditorKit(new HTMLEditorKit()
    public ViewFactory getViewFactory() {
    return new HTMLEditorKit.HTMLFactory() {
    public View create(Element elem) {
    Object o = elem.getAttributes().getAttribute(javax.swing.text.StyleConstants.NameAttribute);
    if (o instanceof HTML.Tag)
    HTML.Tag kind = (HTML.Tag) o;
    if (kind == HTML.Tag.INPUT || kind == HTML.Tag.SELECT || kind == HTML.Tag.TEXTAREA)
    return new FormView(elem)
    protected void submitData(String data)
    showData(data);
    protected void imageSubmit(String data)
    showData(data);
    // Workaround f�r Bug #4529702
    protected Component createComponent()
    if (getElement().getName().equals("input") &&
    getElement().getAttributes().getAttribute(HTML.Attribute.TYPE).equals("radio"))
    String name = (String) getElement().getAttributes().getAttribute(HTML.Attribute.NAME);
    if (radioGroups.get(name) == null)
    radioGroups.put(name, new ButtonGroup());
    ((JToggleButton.ToggleButtonModel) getElement().getAttributes().getAttribute(StyleConstants.ModelAttribute)).setGroup((ButtonGroup) radioGroups.get(name));
    JComponent comp = (JComponent) super.createComponent();
    // Peque�a mejora visual
    comp.setOpaque(false);
    return comp;
    return super.create(elem);
    //editorPane.setText(FORM_TEXT);
    editorPane.setText(texto);
    getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
    private void showData(String data) {
         // ergebnis significa resultado
    StringBuffer ergebnis = new StringBuffer("");
    StringTokenizer st = new StringTokenizer(data, "&");
    while (st.hasMoreTokens()) {
    String token = st.nextToken();
    String key = URLDecoder.decode(token.substring(0, token.indexOf("=")));
    String value = URLDecoder.decode(token.substring(token.indexOf("=")+1,token.length()));
    v.add(value);
    ergebnis.append(" "); ergebnis.append(key); ergebnis.append(": "); ergebnis.append(value); ergebnis.append(" ");
    ergebnis.append(" ");
    JOptionPane.showMessageDialog(this, ergebnis.toString());
    public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame ();
    FormSubmission editor = new FormSubmission ();
    frame.getContentPane().add(editor);
    frame.pack();
    frame.show();
    }

  • How can I create JEditorPane which scrolls to the bottom on every resize?

    JRE 1.3.0
    Included a simple frame with the only control - JEditorPane (contained within JScrollPane). Every time scroll pane size changes, attempt to scroll down to the end of JEditorPane is made.
    The problem is: although everything works 9 times of 10, sometimes editor is scrolled almost to the end, sometimes - to the very top. On the next resize editor is scrolled correctly.
    I think, there are some delayed layout recalculations inside SWING which prevent JEditorPane and/or JScrollPane from knowing actual size.
    Is it possible to force JEditorPane+JScrollPane pair to update dimensions? ( explicit call to doLayout() does not fix anything )
    Thanks
    public class TestFrame extends JFrame
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane jEditorPane1 = new JEditorPane();
    public TestFrame()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    private void jbInit() throws Exception
    this.getContentPane().setLayout(borderLayout1);
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setText("test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");
    jScrollPane1.addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(ComponentEvent e)
    jScrollPane1_componentResized(e);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(jEditorPane1, null);
    void jScrollPane1_componentResized(ComponentEvent e)
    Dimension size = jEditorPane1.getPreferredSize();
    jEditorPane1.scrollRectToVisible( new Rectangle(0, size.height, 0, 0) );
    System.out.println("preferred height=" + size.height);
    }

    Seen this thread?
    Return to previously viewed page

  • 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();

  • Gif animation is not displayed on the JEditorPane

    gif animation file is loaded to this pane, it is played for one time and then changed to "cannot load image" icon. Is it somehow related to the JEditorPane, and if yes, than how???

    So, nobody knows what's the problem?

  • 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?

  • Print HTML file inside JEditorPane

    Hi Guys,
    I'm trying to print the contents of a JEditorPane - actually, a html file that I read and display in that component from the underlying file system. I've had the class that manages the JEditorPane implement Printable - the following is my print() implementation:
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
              throws PrinterException {
              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);
              } else {
                   Graphics2D g2d = (Graphics2D) graphics;
                   g2d.translate(
                        pageFormat.getImageableX(),
                        pageFormat.getImageableY());
                   ivTextArea.paint(g2d);
                   return (PAGE_EXISTS);
    }I've got another method that gets called when a print button is clicked:
    class .... {
      PrintJob pj;
      PageFormat pf;
    private void printMe() {
               if (pj == null) {
                   pj = PrinterJob.getPrinterJob();
                   pf = pj.defaultPage();
                   pf.setOrientation(PageFormat.PORTRAIT);
              pf = pj.pageDialog(pf);
              pj.setPrintable(this, pf);
              try {
                   pj.print();
              } catch (PrinterException e) {
                   throw new RuntimeException(e);
    }Clearly I'm doing smth wrong, since only a single page gets printed and moreover the formatting is awful [text gets cut instead of moving on the next line]. Can someone help?
    Thanks much!

              if (pageIndex > 0) {
                   return (NO_SUCH_PAGE);This is why you only get a single page.
    page gets printed and moreover the formatting is
    awful [text gets cut instead of moving on the next
    line]. Can someone help?Yeah. Your best bet is either to put the editorpane in a scrollpane and just print what's visible, OR, you can take the print graphics object, convert it into a graphics2D object, and call scale on that by comparing component.getWidth/height to PageFormat.getImageableWidth/Height
    I'm attaching my StandardPrint class. It uses the pageable interface to carry the number of pages + page format as well. I'm not sure if I did the scaling here or not, but I've done it before so I know it works :-) Also, I've got methods for previewing the print, which can save a lot of paper.
    Please feel free to have and use this class, but please do not change the package or portray this as your own work
    =============================
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
    //        PageFormat pf = sp.getPageFormat(pageNo);
    //        int width = im.getWidth(null);
    //        int height = im.getHeight(null);
    //        g.setColor(Color.WHITE);
    //        g.fillRect(0, 0, width, height);
    //        double hratio = height / pf.getHeight();
    //        double wratio = width / pf.getWidth();
    //        g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            Graphics2D g = (Graphics2D) gr;
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            int horizontal = getNumHorizontalPages();
            int vertical = getNumVerticalPages();
            int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
            int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
            double ratio = getScreenRatio();
            g.scale(1 / ratio, 1 / ratio);
            g.translate(-horizontal, -vertical);
            if (sp != null) {
                sp.printerPaint(g);
            else {
                c.paint(g);
            g.translate(horizontal, vertical);
            g.scale(ratio, ratio);
            g.translate((int)-format.getImageableX(), (int)-format.getImageableY());
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }>
    Thanks much!

  • JEditorPane HTML link in the same page

    Hi,
    I want to show an HTML page in JEditorPane.
    The HTML page have <a> tags that link to a bookmark in
    the same page, but I can�t show this because I get an error
    like this:
    MalformedURL or similiar.
    I try to do somethig like this:
    public void hyperlinkUpdate(HyperlinkEvent ev)
    ...Editor.setPage(ev.getURL());
    or
    ...Editor.setPage(ev.getDescription());
    without results.
    How can I listen for hyperlinksEvents than link in the same page.
    Thanks

    they dont want to see the first report.
    Is there a way in which the Prompts are also display along with the second report?Then create the same prompt on the second report also.
    Cheers
    Nawneet

  • Refreshing JEditorPane (Urgent) plz help

    hello programmers,
    i'm building an html editor:
    My html editor has a split pane, the 2 pane got of the split pane are JEditorPanes, one on which i write tag and the other i display them,... thankfully all's working great, my syntax is highlighting and the html is displayed well but i've got the following problem:
    when i save a html page , i wanna my browser (on the right side of the slipt pane) to display the html page... it's ok .. it displays it with the method JHTMLEditorPane.setPage(file:/// directory/ file) but the problem is that when i save the page again using the same filename... my html page on the JHTMLEditorPane stays the same... it does not update...
    is their a refresh function for the JEditorPane? how can i update my JHTMLPane to reflect the changes i've brought to it? ONe thing , the page changes when i save it by aother file name..... PLz help it's very urgent!!!!!!!
    Bernard

    Have you tried to close and then re-open the file in your editorpane after you've saved?
    It will work when you change the name because it has to open the file as new. Java can't dynamically update values upon files like C does with pointers.

Maybe you are looking for