DanMc
DanMc

Reputation: 848

How to show a html file inside a JEditorPane

I am trying to show a html file in a jeditorpane.

The file is saved in the project folder and was generated by the program. It is a receipt called FredReceipt.html

I understand how to use a jeditorpane for a url, however I have not been able to understand how I can load a file in through the tutorials etc... I have been reading from the web. I want to load the file in using a relative url. This is what I have at the moment, it's not working (obviously), it's catching the IOException.

public void showReceipt() {
    receiptPanel = new JPanel();
    receiptPanel.setVisible(true);
    receiptPanel.setBackground(new Color(250,251,253)); 
    String url = "FredReceipt.html";
    try {
      JEditorPane htmlPane = new JEditorPane("FredReceipt.html");
      htmlPane.setEditable(false);
      receiptPanel.add(new JScrollPane(htmlPane));
    } catch(IOException ioe) {
      System.err.println("Error displaying " + url);
    }

}

I have also tried using the 'setPage()' method like this:

public void showReceipt() {
    receiptPanel = new JPanel();
    receiptPanel.setVisible(true);
    receiptPanel.setBackground(new Color(250,251,253)); 
    try {
      JEditorPane htmlPane = new JEditorPane();
      htmlPane.setPage(new URL("FredReceipt.html"));
      htmlPane.setEditable(false);
      receiptPanel.add(new JScrollPane(htmlPane));
    } catch(IOException ioe) {
      System.err.println("Error displaying file");
    }

}

FredReceipt.html is obviously not a url, but I have read that files can be read in much the same as urls, I just haven't been able to find the correct way.

I hope my question isn't too dumb, thanks a lot!

Upvotes: 0

Views: 3657

Answers (2)

Sachin Mhetre
Sachin Mhetre

Reputation: 4543

JEditorPane is sort of a fancy text area that can display text derived from different file formats.

The following link may help you.
HTML in JEditorPane

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168825

The file should not be written to the same directory in which the application is installed. Since this data is generated by the application, it seems temporary. In that case, it would be best to put in the java.io.tmpdir, as a temporary file, with a request to delete on exit. Something like this:

File tempDir = new File(System.getProperty("java.io.tempdir"));
File receiptFile = File.createTempFile("FredReceipt", "html", tempDir);
receiptFile.deleteOnExit();
// fill the file with mark-up
// ...
// end filling
editorPane.setPage(receiptFile.toURI().toURL());

Upvotes: 4

Related Questions