java - 打开文档时将图像的 url 转换为实际图像

标签 java image swing actionlistener bufferedimage

当我在文本编辑器中打开文件时。我只在文本 Pane 中获取文件的位置。我在某个地方犯了一个简单的错误还是有更好的方法来做到这一点?我应该使用 ArrayList 来存储图像位置吗?

发生情况的示例:我有一个包含两行的文件...

<小时/>

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

<小时/>

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

仅供引用:textArea 的类型为 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();
}
<小时/>

如果您对此代码有任何疑问或需要澄清,请随时询问。

最佳答案

好的。您在 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();
    }

关于java - 打开文档时将图像的 url 转换为实际图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720027/

相关文章:

java - Project Reactor - 如何按窗口处理结果

java - SoapUI、Maven、TestRails 连接

iphone - 基于图像的 iPhone 应用程序的最佳设计是什么?

java - 当我加载图像列表时仅显示一张图像

java - 禁用具有视觉效果的 JPanel

java - 如何让用户在画线程序中拖动鼠标时看到形状?

java - 在Fragment的布局中显示ZXING条码扫描仪

java - 如何在 Intellij Idea 14 中配置 Tomcat 服务器 8?

java - 图像未出现在 JFrame 中

java - 将方法移动到 SwingWorker