Múltiplos estilos com OutputStream

2 respostas
Adelar

Olá pessoal,

tenho uma dúvida em relação ao uso de estilos com OutputStream customizado. Com o código a seguir:
public class TextComponentStream extends OutputStream {
    private JTextComponent textComponent;
    private Style error;

    public TextComponentStream(JTextComponent textComponent, Style error) {
        this.textComponent = textComponent;
        this.error         = error;
    }

    @Override
    public void write(final int b) throws IOException {
        write(new byte[] {(byte) b}, 0, 1);
    }

    @Override
    public void write(final byte[] b, final int off, final int len) throws IOException {
        final String str = new String(b, off, len);

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {

                    // trava aqui!!!
                    textComponent.getDocument().insertString(textComponent.getDocument().getLength(),
                    										 str,
                    										 error);
                }
                catch (BadLocationException e) {
                	e.printStackTrace();
                }
            }
        });
    }
}
que é acionado com:
...
System.setOut(new PrintStream(new TextComponentStream(result, null)));
System.setErr(new PrintStream(new TextComponentStream(result, SwingUtils.getErrorStyle())));
...
e a classe SwingUtils possui:
public class SwingUtils {

	public static Style getErrorStyle()
	{
		StyleContext sc = new StyleContext();
		Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
		Style errorStyle = sc.addStyle("error", defaultStyle);
		StyleConstants.setForeground(errorStyle, Color.red);

		return errorStyle;
	}

        ...
O código anterior está funcionando. Mas quero atribuir estilos de acordo com certas situações... entretanto ocorre erro quando isto é feito. Quando o estilo na variável error, da classe TextComponentStream, é alterado o programa simplesmente trava na linha com "trava aqui". Não endendi o motivo disso estar ocorrendo. Alguém tem alguma dica? Alterar os estilos desta forma é algo possível?

Obrigado.

[]'s

2 Respostas

ViniGodoy

É possível sim. Você pode postar que tipo de alterações você fez?

Adelar

Consegui achar o problema. :smiley:

Deveria obter o StyledDocument do component para setar o estilo antes da linha “trava aqui”:

Style style = ((JTextPane)textComponent).getStyledDocument().addStyle("custom", null); StyleConstants.setForeground(style, Color.green);
Valeu ViniGodoy. O código da TextComponentStream é de outra dica sua do fórum. Um duplo obrigado. :slight_smile:

Criado 9 de maio de 2011
Ultima resposta 9 de mai. de 2011
Respostas 2
Participantes 2