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

Similar Messages

  • How to export the report in HTML format for desktop application

    Hi,
    i have wrote the JRC desktop application to export the report and i am able to export it in PDF and other formats as mentioned in "ReportExportFormat" API.
    i would like to know is there any API there which can export the report in HTML format.
    i know it would be possible with web based application of JRC, but how can i do it in desktop application?

    There's no mechanism for static HTML pages that displays the report.
    You can use the CrystalReportViewer DHTML viewer, but that's 'interactive'.
    Sincerely,
    Ted Ueda

  • I have a huge file which is in GB and I want to split the video into clip and export each clip individually. Can you please help me how to split and export the videos to computer? It will be of great help!!

    I have a huge file which is in GB and I want to split the video into clip and export each clip individually. Can you please help me how to split and export the videos to computer? It will be of great help!!

    video
    What version of Premiere Elements do you have and on what computer operating system is it running?
    Please review the following workflow.
    ATR Premiere Elements Troubleshooting: PE11: Project Assets Organization for Scene and Highlight Grabs from Collection o…
    But please also determine if your project goal is supported by
    a. format of your source
    and
    b. computer resources
    More later based on details that you will post.
    ATR

  • How do you save changes made in iPhoto, and export the changed file.  It keeps reverting back to the original.

    How do you save changes made in iPhote, and export the changed picture file? When I select export, current format, it reverts to the original, wiping out all my work.

    Try trash the com.apple.iPhoto.plist file from the HD/Users/ Your Name / library / preferences folder.
    (On 10.7 or later: Hold the option (or alt) key while clicking on the Go menu in Finder to access the User Library)
    (Remember you'll need to reset your User options afterwards. These include minor settings like the window colour and so on. Note: If you've moved your library you'll need to point iPhoto at it again.)
    What's the plist file?
    For new users: Every application on your Mac has an accompanying plist file. It records certain User choices. For instance, in your favourite Word Processor it remembers your choice of Default Font, on your Web Browser is remembers things like your choice of Home Page. It even recalls what windows you had open last if your app allows you to pick up from where you left off last. The iPhoto plist file remembers things like the location of the Library, your choice of background colour, whether you are running a Referenced or Managed Library, what preferences you have for autosplitting events and so on. Trashing the plist file forces the app to generate a new one on the next launch, and this restores things to the Factory Defaults. Hence, if you've changed any of these things you'll need to reset them. If you haven't, then no bother. Trashing the plist file is Mac troubleshooting 101.

  • Using Powershell Script Run simple query in MS Access 2007 and export the results of query to Excel

    Hi Experts,
    I have a Access 2007 DB file and 2 Big tables inside that (bigger than the size that can be easily handled by MS Excel 2007).
    My requirement is automate using powershell scripts the below things.
    1. Create a SQL query in Access DB and save that in access DB
    2. Run the saved query and export the result in excel sheet where I can create the charts and Pivots. Thanks in advance
    Prajesh

    Do you have to use the Access query, couldn't you just recreate the query in Powershell?  Here's a link with good info that references an existing script for querying an Access database:
    http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/13/hey-scripting-guy-can-i-query-a-microsoft-access-database-with-a-windows-powershell-script.aspx
    Once you have your dataset you can pipe it to
    Export-Csv -NoType c:\pathtofile\output.csv

  • How to import and make the content of the original PDF document editable and preserves the pdf appearance and retains existing fields and formatting in LiveCycle

    Can someone tell me how I can see my content (artwork and text) after I import  it into LiveCycle Designer ES4?  I like to import and make the content of the original PDF document editable; preserves the pdf appearance and retains existing fields and formatting, then allow me to do the modifications and save it back into the original PDF document with changes. I have tried everything but still cannot see my content(artwork and Text) of my original PDF after importing it into LiveCycle. All I see are is a blank page with the formatting and layout of where my artwork and text should be. I like to see everything if possible so after I make my change I will know how it will look when I save it back into the PDF and open it in Acrobat Reader.

    Can someone tell me how I can see my content (artwork and text) after I import  it into LiveCycle Designer ES4?  I like to import and make the content of the original PDF document editable; preserves the pdf appearance and retains existing fields and formatting, then allow me to do the modifications and save it back into the original PDF document with changes. I have tried everything but still cannot see my content(artwork and Text) of my original PDF after importing it into LiveCycle. All I see are is a blank page with the formatting and layout of where my artwork and text should be. I like to see everything if possible so after I make my change I will know how it will look when I save it back into the PDF and open it in Acrobat Reader.

  • I downloaded the Final Cut Pro X trial but my movie is 17 minutes long but it will only Share to Quick time 6:55 minutes. How do I fix this and export the full 17 minutes?

    I downloaded the Final Cut Pro X trial but my movie is 17 minutes long but it will only Share to Quick time 6:55 minutes. How do I fix this and export the full 17 minutes?

    Thank You. Im trying to export everything. I pressed command A and then did the Share button. Ill attach the screenshot please let me know if I need to change something.

  • Import and export the database table

    I would like to know what is the syntax of using imp.exe and exp.exe to import and export the database table?
    Could anyone teach me what is the syntax and how could do the export and import in the Forms?
    Thanks a loT~

    try: imp help=yes
    Or read the documentation online on OTN.

  • Is it possible to use markers in a Premiere Pro sequence such as Chapter / Comment / Segmentation and export the XMP metadata for a database so that when the video is used as a Video On-Demand resource, a viewer can do a keyword search and jump to a relat

    Is it possible to use markers in a Premiere Pro sequence such as Chapter / Comment / Segmentation and export the XMP metadata for a database so that when the video is used as a Video On-Demand resource, a viewer can do a keyword search and jump to a related point in the video?

    take have to take turns
    and you have to disable one and enable the other manually

  • How can I split my Dj mix into separate tracks and export the tracks

    How can I split my Dj mix into separate tracks and export the tracks. I'm trying to burn my Dj mix to cd and I don't want it to be one long track.

    Henryfrommo wrote:
    How can I split my Dj mix into separate tracks and export the tracks.
    http://www.bulletsandbones.com/GB/GBFAQ.html#exportsections
    (Let the page FULLY load. The link to your answer is at the top of your screen)

  • How to import and export the screen parameters

    hi all
    how to import and export the parameters of the screen
    i need to export all the parameters and then import it
    and also how to export and import a variable to the memory
    thanks and regards
    naval bhatt

    Hi,
    Check this example for exporting and importing to memory..
    DATA: V_VALUE(2) VALUE '2'.
    EXPORT V_VALUE = V_VALUE TO MEMORY ID 'ZTEST'.
    IMPORT V_VALUE = V_VALUE FROM MEMORY ID 'ZTEST'.
    Thanks,
    Naren

  • I have two Macs: an MBA and the new iMac.  Is there a way to have iTunes and all the content in it identical on both machines?

    I have two Macs: an MBA and the new iMac.  Is there a way to have iTunes and all the content in it identical on both machines?

    Yes you can copy the content to your new machine and use Home Sharing to keep the content identical
    Connect the two machines via an ethernet cable it is 3 times faster than Wifi. Turn wifi off on one machine to enforce ethernet connection
    In System Preferences, Sharing turn on File Sharing
    Then
    Copy the music/itunes folder from the Macbook pro to the music/ folder on the imac
    Both machines should now have the same library
    Disconnect H the ethernet cable
    Set up Home Sharing and under Settings at the bottom of the Home Sharing page. Select to transfer new purchases.
    Do the same on the other machine.
    Then when you r machines are connected by wifi and each time you start itunes it will transfer your new purchases
    Setting up home sharing

  • I'd like to sync my iTouch and iPad with my PC, and have the content (both iTunes and uploaded music) on the devices override the content on the PC, but cannot seem to find a option to do that. Can anyone help me?

    I had to have my PC wiped clean and the OS re-loaded. I thought I backed up everything  on my iTouch and iPad correctly, but when I try to sync, I'm getting a message that if I continue with the sync, I will lose everything on my device. I'd like to sync and have the content (both iTunes purchased music/apps and uploaded music) override the content on my PC, but am unable to find a way to do that. I have the first gen iTouch that does not support iCloud. Can anyone help?

    My question is, can I listen to all the audio that come out from the ipad (movies online, games, Goear…) or only to the music from iTunes library?
    On the iPad you can stream videos, photos, or music from the Video, Photos, Music, and YouTube apps to an Apple TV OR just stream music to an AirPort Express Base Station.

  • Search for a tag in xml and modify the content

    Hi,
    I am quite new to using xml db and i want to know how to search a xml, modify a tag value inside xml and replace the content in xml.
    Please help me to find a solution for this.
    Regards,
    Sprightee

    Hi,
    First important thing : give your database version (SELECT * FROM v$version).
    Please also provide some sample data :
    - a typical XML document you're working with (or abridged version)
    - explain what change(s) you want to do, or give expected output
    - if you're using a table to store the XML (which is preferred), give the DDL

  • How can i check messages sent to device through my Verizon account online? i want to open the messages and see the contents.

    How can i check messages sent to device through my Verizon account online? i want to open the messages and see the contents.

        I know it's beneficial to be able to check your message content ArmyQueer. Verizon messages offers a wide variety of convenient options to manage messaging. What make and model device is this? When did you download the application on it? Please be aware you will only be able to see content after the app had been downloaded and installed. Content prior to the app being active will not be available. Here's a link with additional info. http://vz.to/1k3gBxd
    JonathanK_VZW
    VZWSupport
    Follow Us on Twitter@VZWSupport

Maybe you are looking for

  • Can't customize track information on Itunes 11.01

    This might take awhile.  A month ago, I purchased a new MBP which is running Itunes 11.01.  So, I had to redo all of my playlists.  I have well over a million different audio files/music tracks.  I download A LOT of live music from different artists.

  • Application Express 3.0.1 Upgrade

    I am running Application Express 2.0.2.00.49 and the backend is Oracle 10.2.0.1.0 on Linux 32bit and 64bit 9.3 Susie Servers. I want to upgrade to the new 3.0.1 Application Express and wonder what steps or tricks there might be waiting for me when I

  • Running a Struts Example Program

    Hello, Im working on a course work about jakarta struts & I dowloaded an example program from a site, but I can not run it as it always gives me the same error(below). I also tried to run one simple one that I created my self, but still doesn't work

  • Object too small to select on design canvas

    I have created 14px by 14px images for a mini navigation area, and added them to a set of Image components.  Due to the very small size, these objects are not selectable on the Xcelsius design canvas, although I can select them in the object browser.

  • Bad Parameter ! box

    Hello, I have a message box which pops when I run my code, but it doesn't look like a error with my code, its a smaller warning sign message box saying "Bad Parameter" I haven't put a alert box like this anywhere in my code. My code is using a shockw