2012-01-03 31 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