用户选择的图像可以直接插入JEditorPane吗? [英] Can a user-chosen image be inserted directly into a JEditorPane?

查看:97
本文介绍了用户选择的图像可以直接插入JEditorPane吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是打开一个过滤jpeg,gif和png图像的JFilechooser,然后获取用户的选择并将其插入到JEditorPane中。可以这样做吗?还是我在尝试一些不可能的事情以下是我的程序示例。(insert是JMenuItem,mainText是JEditorPane)

What I am trying to do is open up a JFilechooser that filters jpeg,gif and png images, then gets the user's selection and inserts it into the JEditorPane. Can this be done? or am i attempting something impossible? Here is a sample of my program.(insert is a JMenuItem and mainText is a JEditorPane)

insert.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent e){
    JFileChooser imageChooser = new JFileChooser();
      imageChooser.setFileFilter(new FileNameExtensionFilter("Image Format","jpg","jpeg","gif","png"));
                int choice = imageChooser.showOpenDialog(mainText);
                if (choice == JFileChooser.APPROVE_OPTION) {
                mainText.add(imageChooser.getSelectedFile());
                }
        }
    });

我尝试做的是使用add方法,我知道这是错的,但只是为了给你一个我想要做什么的想法。
在你投诉之前,我很抱歉代码格式化,我真的不知道所有被认为是好的或坏的风格的惯例。
非常感谢。

What i tried to do is use the add method, i know it's wrong but just to give you an idea of what i'm trying to do. Before you complain, i'm sorry about the code formatting, i don't really know all the conventions of what is considered good or bad style. Thank you very much.

这是我用来保存html文件的代码部分。

This is the part of the code i use to save the html file.

else if (e.getSource() == save) {
        JFileChooser saver = new JFileChooser();
        saver.setFileFilter(new FileNameExtensionFilter(".html (webpage format)" , "html"));
        int option = saver.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(saver.getSelectedFile().getPath()));
                out.write(mainText.getText());
                out.close();
            } catch (Exception exception) {
                System.out.println(exception.getMessage());
            }
        }
    }


推荐答案

更容易使用JTextPane。然后你可以在文本的任何地方使用insertIcon(...)。

Its easier to just use a JTextPane. Then you can use insertIcon(...) anywhere in the text.

编辑:

我从来没有尝试操作HTML有很多运气,但我之前使用过如下代码:

I have never had much luck trying to manipulate HTML but I've used code like the following before:

HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
text = "<a href=\"abc\">hyperlink</a>";
editorKit.insertHTML(doc, textPane.getCaretPosition(), text, 0, 0, HTML.Tag.A);

因此可能代码与IMG标签类似。

So presumably the code would be similiar for the IMG tag.

这篇关于用户选择的图像可以直接插入JEditorPane吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆