You want to put an Icon in a jTextPane with Text and want to get this Icon back?
1. Create your Icon using a Style
- create a style
- add it to the jTextPane
- use the StyleConstants.setIcon(Style s, Icon c) to define your style
- create a StyledDocument
- return a StyledDocument with the method getStyledDocument() dans jTextPane
- uuse the method insertString(int pos, String str, Style s) to insert your Icon
2.Find the Style in which you put your Icon and get it back!
- get a DefaultStyledDocument from jTextPane with the method getStyledDocument with a typecast (DefaultStyledDocument)
- get a Enumeration of all the name of your Style use in this Document with getStyleNames
- run through the Enumeration
- select the good name (if you give them good name, you can use string match up for example)
- get your style from the name with getStyle(String name) from DefaultStyledDocument
- get the Icon in this Style with StyleConstants.getIcon(Style s);
And it work!!!
Here is an example. I create 2 jTextPane. In the first one, I put the Icon, then I get it back and put it in the Second.
//Create the Icon and put it in the jTextPane
Style style = jTextPane1.addStyle("Icon", null);
StyleConstants.setIcon(style, new ImageIcon("ImageLink"));
StyledDocument doc = jTextPane1.getStyledDocument();
try{
doc.insertString(0, "Texte inutil", style);
}catch (Exception e){
//rien faire
}
//Get it back and put it back in the second jTextPane
DefaultStyledDocument dDoc = (DefaultStyledDocument)jTextPane1.getStyledDocumen t();
Enumeration list = dDoc.getStyleNames();
String styleName = (String)list.nextElement();
Style style = dDoc.getStyle(styleName);
Icon a = StyleConstants.getIcon(style);
jFrame1.setVisible(true);
jTextPane2.setText("");
Style style2 = jTextPane2.addStyle("ICON2", null);
StyleConstants.setIcon(style2, a);
StyledDocument doc2 = jTextPane2.getStyledDocument();
try{
doc2.insertString(0, " ", style2);
} catch (Exception e){
//rien faire
}
If you know a better way, pls let me know.
N.B. How do it put my code in a code box?
|