2012-01-03 70 views
0

当我在文本编辑器中打开文件时。我只是在文本窗格中获取文件的位置。我在某处做了一个简单的错误还是有更好的方法来做到这一点?我应该使用ArrayList来存储图像位置吗?打开文档时将图像的url转换为实际图像

发生了什么事的例子:我有一个有两行的文件...


C:\ ... \ pic.png
(图片说明)


当我尝试打开文件(在我将其保存在文本编辑器中后),它显示了图片的实际位置。我想能够使用BufferedImage获取目录并将图像添加到JTextPane。否则(如果文本不是位置),只需将文本添加到文本窗格。

FYI:文本类型为的JTextPane

代码,打开我的文件


// sb is my StringBuffer 

try 
{ 
    b = new BufferedReader(new FileReader(filename)); 
    String line; 

    while((line=b.readLine())!=null) 
    { 
     if (line.contains("C:\\...\\Pictures\\")) 
     { 
      BufferedImage image = ImageIO.read(new File(line)); 
      ImageIcon selectedPicture = new ImageIcon(image); 
      textArea.insertIcon(selectedPicture); 
     } 

     sb.append(line + "\n"); 
     textArea.setText(sb.toString()); 
    } 

    b.close(); 
} 

如果您对这个代码有任何疑问或需要澄清,不要犹豫,问。

+0

这是什么文件?你为什么不简单地使用HTML文件? – 2012-01-04 22:14:14

+0

如果在执行'textArea.insertIcon'后执行了'textArea.setText',那么不会更改所有内容吗?你的输入文件看起来如何? – 2012-01-04 22:20:04

+0

@JBNizet这是一个我正在尝试用我的文本编辑器应用程序打开的文本文件。 – Rob 2012-01-05 00:40:18

回答

1

好的。您将内容设置为JTextPane的方式不正确。 基本技巧是从JTextPane中获取StyleDocument,然后在文档上设置Style。样式基本上解释了组件如何呈现。例如,文本格式,图像图标,间距等。

鉴于下面的代码会帮助您开始。

JTextPane textPane = new JTextPane(); 
    try { 
     BufferedReader b = new BufferedReader(
       new FileReader("inputfile.txt")); 
     String line; 
     StyledDocument doc = (StyledDocument) textPane.getDocument(); 

     while ((line = b.readLine()) != null) { 

      if (line.contains("/home/user/pictures")) { 
       Style style = doc.addStyle("StyleName", null); 
       StyleConstants.setIcon(style, new ImageIcon(line)); 
       doc.insertString(doc.getLength(), "ignore", style); 

      } else { 
       Style textStyle = doc.addStyle("StyleName", null); 
       //work on textStyle object to get required color/formatting. 
       doc.insertString(doc.getLength(), "\n" + line, textStyle); 
      } 
     } 

     b.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
+0

哇,非常酷!非常感谢你的帮助(尤其是示例)。 – Rob 2012-01-05 21:37:19