2012-04-30 55 views
0

我试图在jeditorpane中显示html文件。如何在JEditorPane中显示html文件

该文件保存在项目文件夹中,由程序生成。这是一个名为FredReceipt.html

我知道如何使用一个url的jeditorpane,但我一直无法理解如何通过教程等加载文件...我一直在阅读网络。我想使用相对URL加载文件。这是我目前所拥有的,它不工作(显然),它捕捉到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); 
    } 

} 

我也曾尝试使用'setPage()方法是这样的:

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显然不是一个网址,但我已阅读,文件可以被读取多少与网址相同,我只是无法找到正确的方法。

我希望我的问题不是太愚蠢,非常感谢!

+0

你是什么意思“它不工作”?请明确点。 – twain249

+0

对不起,它正在赶上IOException – DanMc

+0

我在找到解决方案后就立即找到解决方法,并提出了这个问题。对不起浪费任何时间。当我被允许时我会发布它(由于不到100位代表,我无法发布几个小时)。 – DanMc

回答

4

不应将该文件写入应用程序所在的同一目录中。由于这些数据是由应用程序生成的,因此这似乎是暂时的。在这种情况下,最好将java.io.tmpdir作为temporary file,请求delete on exit。类似这样的:

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

JEditorPane是一种花哨的文本区域,可以显示来自不同文件格式的文本。

以下链接可能对您有所帮助。
HTML in JEditorPane