Boa tarde a todos
Gostaria de pedir uma luz a quem puder me ajudar. Gostaria de criar um editorzinho de texto, que muda a cor da palavra, conforme o usuário digita. Consigo alterar as cores do texto inteiro ou alterar as cores a partir de onde está o cursor, mas não consigo altera as cores de uma única palavra já digitada. A idéia é tentar fazer algo como um leitor de XML, porém com algumas tags específicas. Até agora todo o meu progresso se resume no seguinte código:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class EditorTexto extends JFrame implements KeyListener{
private JTextPane tpTeste;
private JScrollPane spTeste;
private String ultimoTexto="";
public static void main(String args[]){
new EditorTexto();
}
public EditorTexto(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DocumentoEstiloso doc = new DocumentoEstiloso();
tpTeste = new JTextPane();
tpTeste.setStyledDocument(doc);
tpTeste.addKeyListener(this);
spTeste = new JScrollPane(tpTeste);
spTeste.setPreferredSize(new Dimension(400,400));
getContentPane().add(spTeste);
setVisible(true);
pack();
}
private void redStile(){
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.red);
tpTeste.setCharacterAttributes(aSet, false);
}
private void blueStile(){
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.blue);
//Já descobri que se mudar para "true" onde está "false", consigo mudar todas as palavras
//e do jeito que está o java altera apenas as próxima palavras
tpTeste.setCharacterAttributes(aSet, false);
}
//Monitoro o teclado
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyChar() == KeyEvent.VK_SPACE){
//Capturo o último texto digitado
ultimoTexto = tpTeste.getText().split(" ")[tpTeste.getText().split(" ").length-1];
redStile();
}else if(arg0.getKeyChar() == KeyEvent.VK_A){
blueStile();
}
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}
Pelo que li não tem maneira de fazer isto com o JTextArea, mas se alguém conhecer POR FAVOR me mostre. Resumindo consigo alterar a partir de uma parte do texto para frente e consigo trocar a cor de todo o texto, porém só não consigo fazer aquilo que preciso: achar uma palavra recém digitada e alterar a cor dela.
No aguardo de ajuda,
Inté…