tags:

views:

183

answers:

1

I am working on a bug in this program where it should be able to save the contents of a JTextPane to a formatted HTML file. The code that is currently there save a file containing just the tags but no content. The page appears blank but all the correct <p> and <font> tags are there with the correct colour set etc.

HTMLDocument htmlDoc = (HTMLDocument) output.getDocument();
FileWriter fw = new FileWriter(logFile);
HTMLWriter htmlWriter = new HTMLWriter(fw, htmlDoc);
htmlWriter.write();
fw.flush();
fw.close();

That is the code as it is currently. output is the JTextPane object. It doesn't seem right to be that the Document object returned from getDocument() is being casted directly into a HTMLDocument object.

Does anyone know what would make this work?

+2  A: 

The reason is that the JTextPane contructor takes a StyledDocument as argument. So I think while creating it you passed a HTMLDocument to its constructor. That way it works.!! So as long as you know that you have passed HTMLDocument to its constructor or you have used output.setDocument(new HTMLDocument()) or something, it is safe to do that cast!!

Suraj Chandran
I have found that getDocument() returns an HTMLDocument object so that is fine but it still doesn't write the content. Creating the JTextPane no arguments are passed to the constructor although setContentType("text/html") is called on it.
Android
setContentType("text/html") will end up calling setDocument() anyway. As far working is concerned, for me it works perfectly fine.
Suraj Chandran
Could you please post your code then because I can't see what I am doing wrong.
Android
pane.setContentType("text/html"); pane.setText("<html><b>Suraj</b></html>"); frame.add(pane); JButton btn = new JButton("Save"); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { FileWriter fw = new FileWriter("C:\\abc.html"); HTMLWriter hw = new HTMLWriter(fw, (HTMLDocument) pane.getDocument()); hw.write(); fw.flush(); fw.close(); } catch (Exception ex) { } } });
Suraj Chandran
If you like the answer please do consider giving an up vote:)
Suraj Chandran
Oh!! Sorry for the formatting...comments dont seem to return formatting
Suraj Chandran