2013-08-12 105 views
0

我找到了here:我在寻找的东西,但我仍然有一些问题。重新加载编辑器区块

这是我的动作代码:

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException { 

    jEditorPane1.setContentType("text/html"); 


    int returnVal = FileChooser1.showOpenDialog(this); 
    if (returnVal == FileChooser1.APPROVE_OPTION) { 


String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile()); 
    jEditorPane1.setText(image); 

    } 
} 

这里是发生了什么,你可以看到图像不加载的屏幕截图。 http://postimg.org/image/agc665ih1/

但是,如果我保存文件(带保存按钮)并重新打开相同的文件(打开按钮),图像就在那里,并完美加载。

我已经尝试过.repaint()和.revalidate()方法,但不工作.. 任何想法?

回答

0

这可能是在JEditorPane页面中设置路径的问题。使用这个:

String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath()); 

我假设你已经为JEditorPane选择了合适的editorKit。

+0

不,我得到了相同的结果:/ 对JEditorPane我选择了一个HTMLEditorKit(),代码看起来像: \t \t jEditorPane1.setEditorKit(新一个HTMLEditorKit()) ; – DJack

+0

你如何打开图像,你可以粘贴该代码? – Ashwani

+0

我认为这不是问题,但我会尽快粘贴代码,因为我必须等待几个小时才能回答自己的问题。:) – DJack

0

所以现在我可以用我的代码回答。我正在使用这个类作为文件选择器:

import java.io.File; 

import javax.swing.filechooser.FileFilter;

类jpgfilter扩展的FileFilter {

public boolean accept(File file) { 
     return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg"); 
    } 

    public String getDescription() { 

     return "JPG image (*.jpg)"; 
    } 

}

而在我的主类我有这样的:

FileChooser1 = new javax.swing.JFileChooser(); 
    FileChooser1.setDialogTitle("Choose your image:"); 
    FileChooser1.setFileFilter(new jpgfilter()); 

就是这样。

0

所以我实际上找到了某种解决方案,但我认为有太多的代码,我应该很容易做到..我实际上插入图像,同时保存并打开EditorPane的内容为.html文件。

代码:

jEditorPane1.setContentType("text/html"); 

    int returnVal = FileChooser1.showOpenDialog(this); 
    if (returnVal == FileChooser1.APPROVE_OPTION) { 

     String image = String.format("<img src=\"%s\">", FileChooser1 
       .getSelectedFile().getPath()); 

     jEditorPane1.setText(image); 

     String type = jEditorPane1.getContentType(); 

     OutputStream os = new BufferedOutputStream(new FileOutputStream(
       "/Library/java_test/temp" + ".html")); 

     Document doc = jEditorPane1.getDocument(); 
     int length = doc.getLength(); 

     if (type.endsWith("/rtf")) { 
      // Saving RTF - use the OutputStream 
      try { 
       jEditorPane1.getEditorKit().write(os, doc, 0, length); 
       os.close(); 
      } catch (BadLocationException ex) { 
      } 
     } else { 
      // Not RTF - use a Writer. 
      Writer w = new OutputStreamWriter(os); 
      jEditorPane1.write(w); 
      w.close(); 
     } 

     String url = "file:///" + "/Library/java_test/temp" + ".html"; 

     jEditorPane1.setPage(url); 

    } 
相关问题