Search code examples
javahtmlimagejfilechooserjeditorpane

Can a user-chosen image be inserted directly into a 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());
                }
        }
    });

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

Solution

  • 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.