how to load html to styledocument

I'm using a StyleDocument to display my content in a JTextPane. I searched for a while and saw that I can write with the HTMLEditorKit the document I get from the textpane to a file. But when I want to read this file with the HTMLEditorKit it doesn't parse in the right document. I get two different results:

  1. I get the plain html code in my textpane
  2. I get no content in my textpane

Saving:

Document doc = textpane.getStyledDocument();
HTMLEditorKit kit = new HTMLEditorKit();
kit.write(new FileOutputStream("path"), doc, 0, doc.getLength());

Loading (2 versions):

HTMLEditorKit kit = new HTMLEditorKit();
Document doc = null;
Document doc2 = kit.createDefaultDocument();

kit.read(new FileInputStream("path"), doc, 0);
kit.read(new FileInputStream("path"), doc2, 0);

textpane.setDocument(doc);
textpane.setDocument(doc2);

Upvotes: 4

Views: 1607

Answers (4)

Shikatsu
Shikatsu

Reputation: 307

You can display your html in a JEditorPane like this:

    private void AboutGame()
    {
        JEditorPane Log = CreateEditorPane("AboutGame.html");

        JScrollPane LogScrollPanel = new JScrollPane(Log);
        LogScrollPanel.setVerticalScrollBarPolicy
                            (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        LogScrollPanel.setPreferredSize(new Dimension(800, 400));
        LogScrollPanel.setMinimumSize(new Dimension(10, 10));

        Object Message = LogScrollPanel;

        JOptionPane.showMessageDialog(null, 
                                          Message, "About Game", 1);
    }

Upvotes: 0

Vishal K
Vishal K

Reputation: 13066

I guess that you don't want to change the code written to save. So let it to be as it is.
You need to change the LOADING code as follows:

HTMLEditorKit kit = new HTMLEditorKit();
StyledDocument doc2 = (StyledDocument)kit.createDefaultDocument();
kit.read(new FileInputStream(file), doc2, 0);
pane = new JTextPane();
pane.setEditorKit(kit);//set EditorKit of JTextPane as kit.
pane.setDocument(doc2);

For example consider the code Demo given below:

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class HTMLKit extends JFrame implements ActionListener{
     public static final String text = "As told by Wikipedia\n"
    +"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
    + "It is specifically designed to have as few implementation "
    + "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
    + "meaning that code that runs on one platform does not need to be recompiled to run on another. "
    + "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
    + "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
    + "languages in use, particularly for client-server web applications, with a reported 10 million users.";
    JTextPane pane ;
    DefaultStyledDocument doc ;
    StyleContext sc;
    JButton save;
    JButton load;
    JScrollPane jsp;
    public static void main(String[] args) 
    {
        try 
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    HTMLKit se = new HTMLKit();
                    se.createAndShowGUI();
                }
            });
        } catch (Exception evt) {}
    }
    public void createAndShowGUI()
    {
        setTitle("TextPane");
        sc = new StyleContext();
        doc = new DefaultStyledDocument(sc);
        pane = new JTextPane(doc);
        save = new JButton("Save");
        load = new JButton("Load");
        JPanel panel = new JPanel();
        panel.add(save);panel.add(load);
        save.addActionListener(this);load.addActionListener(this);
        final Style heading2Style = sc.addStyle("Heading2", null);
        heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
        heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
        heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
        heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
        try 
        {
            doc.insertString(0, text, null);
            doc.setParagraphAttributes(0, 1, heading2Style, false);
        } catch (Exception e) 
        {
            System.out.println("Exception when constructing document: " + e);
            System.exit(1);
        }
        jsp = new JScrollPane(pane);
        getContentPane().add(jsp);
        getContentPane().add(panel,BorderLayout.SOUTH);
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent evt)
    {
        if (evt.getSource() == save)
        {
            save();
        }
        else if (evt.getSource() == load)
        {
            load();
        }
    }
    private void save()
    {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Save");
        int returnVal = chooser.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = chooser.getSelectedFile();
            if (file != null)
            {
                try
                {
                    Document doc = pane.getStyledDocument();
                    HTMLEditorKit kit = new HTMLEditorKit();
                    kit.write(new FileOutputStream(file), doc, 0, doc.getLength());
                    JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            else 
            {
                JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    private void load()
    {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Open");
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = chooser.getSelectedFile();
            if (file!= null)
            {
                try
                {
                    HTMLEditorKit kit = new HTMLEditorKit();
                    StyledDocument doc2 = (StyledDocument)kit.createDefaultDocument();
                    kit.read(new FileInputStream(file), doc2, 0);
                    JTextPane pane1 = new JTextPane();
                    pane1.setEditorKit(kit);
                    pane1.setDocument(doc2);
                    repaint();
                    jsp.setViewportView(pane1);
                    repaint();
                    JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
            else 
            {
                JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }

}

Upvotes: 0

nattyddubbs
nattyddubbs

Reputation: 2095

When you initialize your JTextPane add the following line: textpane.setContentType("text/html");

Change Saving to look like this:

Document document = textpane.getStyledDocument();
EditorKit kit = textpane.getEditorKit();
kit.write(new FileOutputStream(new File("path")), doc, 0, doc.getLength());

Change Loading to look like this:

EditorKit kit = pane2.getEditorKit();
Document doc = kit.createDefaultDocument();
kit.read(new FileInputStream(new File("path")), doc, 0);
textpane.setDocument(doc);

Using this setup in my test environment I was able to set the text in a JTextPane to some html, get the html from the pane, write it to a file and subsequently read it back from that same file. I didn't see any reason to use a HTMLEditorKit as you are not doing anything html specific however you can change that as you see fit.

Upvotes: 2

tjordan
tjordan

Reputation: 104

You need to set the content type of the JTextPane to "text/html" JEditorPane API. This should display the html correctly then.

Upvotes: 0

Related Questions