问题
I'm working in a wysiwyg editor, with a jEditorPane, right now I'm trying to insert images via a JFileChooser into de editorpane, but it only inserts one image, I don't know how to do it, any ideas?
Here's how I'm inserting the image:
public void Imagen(){
int im = ImageChooser.showOpenDialog(ImageChooser);
if (im == JFileChooser.APPROVE_OPTION){
String Path = String.format("<img src=\"file:\\%s\"alt=\"Image\">", ImageChooser.getSelectedFile().getAbsolutePath());
EditorPane.setText(Path );
System.out.println(Path);
}
}
回答1:
Well... somehow I managed to solve my problem, it seems setText
wasn't good at all. What I did instead was get the path with .getAbsolutePath
(I printed it just to be sure I was doing it the right way) and then insert it with the HTMLEditorKit
, you got to be careful here 'cause I wasn't able to see the image at first because I was writing it incorrectly, any way here my solution:
public void Imagen(){
int im = ImageChooser.showOpenDialog(ImageChooser);
if (im == JFileChooser.APPROVE_OPTION){
System.out.println("Loading Image...");
int caretPos = EditorPane.getCaretPosition();
HTMLEditorKit e = new HTMLEditorKit();
try {
String Path = String.format( ImageChooser.getSelectedFile().getAbsolutePath());
System.out.println(Path);
e.insertHTML(document, caretPos,"<img src=\"file:\\"+Path+"\" alt=\"some_text\">" , 0, 0, HTML.Tag.IMG);
// <img src="url" alt="some_text">
} catch (BadLocationException ex) {
Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Nothing loaded");}
}
来源:https://stackoverflow.com/questions/25839668/jeditorpane-handling-local-images