【问题标题】:How to show a html file inside a JEditorPane如何在 JEditorPane 中显示 html 文件
【发布时间】:2012-05-09 18:27:36
【问题描述】:

我正在尝试在 jeditorpane 中显示一个 html 文件。

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

我了解如何将 jeditorpane 用于 url,但是我无法理解如何通过教程等加载文件......我一直在从网上阅读。我想使用相对 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 显然不是 url,但我读过文件可以像 url 一样读取,我只是没能找到正确的方法。

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

【问题讨论】:

  • “它不工作”是什么意思?具体一点。
  • 对不起,它正在捕获 IOException
  • 在我失去希望并提出这个问题之后,我设法找到了解决方案。很抱歉浪费了大家的时间。我会在允许的情况下发布(由于代表人数不足 100 人,我无法在几个小时内发布)。

标签: java html swing file jeditorpane


【解决方案1】:

不应将文件写入安装应用程序的同一目录。由于此数据是由应用程序生成的,因此它似乎是暂时的。在这种情况下,最好将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

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 1970-01-01
      • 2012-10-24
      • 2012-11-26
      • 2013-11-04
      • 2010-10-08
      • 1970-01-01
      • 2019-06-30
      • 2013-02-09
      相关资源
      最近更新 更多