Can a user-chosen image be inserted directly into a JEditorPane?

我的未来我决定 提交于 2019-12-13 03:46:59

问题


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());
                }
        }
    });

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.

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());
            }
        }
    }

回答1:


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

Edit:

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);

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




回答2:


This should do it:

mainText.setContentType("text/html");
String image = String.format("<img src=\"%s\">", imageChooser.getSelectedFile());
mainText.setText(image);


来源:https://stackoverflow.com/questions/2951357/can-a-user-chosen-image-be-inserted-directly-into-a-jeditorpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!