Napisałem sobie klasę (na podstaiwe tego, co znalazłem w necie):
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.IOException;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Emotes extends JEditorPane {
public Emotes() {
super();
this.setEditorKit(new StyledEditorKit());
this.initListener();
}
private void replace (String text, StyledDocument doc, ImageIcon icon, int start, String what) throws BadLocationException
{
int i = text.indexOf(what);
while(i >= 0)
{
final SimpleAttributeSet attrs = new SimpleAttributeSet(doc.getCharacterElement(start+i).getAttributes());
if (StyleConstants.getIcon(attrs) == null)
{
StyleConstants.setIcon(attrs, icon);
doc.remove(start+i, what.length());
doc.insertString(start+i,what, attrs);
}
i = text.indexOf(what, i+what.length());
}
}
private void initListener() {
getDocument().addDocumentListener(new DocumentListener(){
@Override
public void insertUpdate(DocumentEvent event) {
final DocumentEvent e=event;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (e.getDocument() instanceof StyledDocument) {
try {
StyledDocument doc=(StyledDocument)e.getDocument();
int start= Utilities.getRowStart(Emotes.this,Math.max(0,e.getOffset()-1));
int end=Utilities.getWordStart(Emotes.this,e.getOffset()+e.getLength());
String text=doc.getText(start, end-start);
replace(text, doc, createEmoticon("wink.png"), start, ";)");
replace(text, doc, createEmoticon("wink.png"), start, "<wink>");
replace(text, doc, createEmoticon("sad.png"), start, ":(");
replace(text, doc, createEmoticon("sad.png"), start, "<sad>");
replace(text, doc, createEmoticon("smile.png"), start, ":)");
replace(text, doc, createEmoticon("smile.png"), start, "<smile>");
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});
}
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
}
static ImageIcon createEmoticon(String icon)
{
BufferedImage img = null;
try
{
img = ImageIO.read(new File(icon));
Graphics g = img.getGraphics();
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}catch (IOException ex)
{
}
return new ImageIcon(img);
}
}
No i to działa. Ale mam główne okno aplikacji dziedziczące po JFrame, który ma przycisk "Napisz", po którego wciśnięciu pokazuje się okienko JDialog, o tak:
Pisadlo pisz = new Pisadlo(this, true);
pisz.setVisible(true);
w którym mam JScrollPane, a na nim JEditorPane. Kiedy chcę dodać "custom code", żeby w tym okienku też mi zamieniało tekst na emotki, o tak:
to to co prawda działa, ale nie zamienia ":)" na obrazki. Co jest źle?