Pregunta

I'm having difficulties with my logger that I embedded into a JTextArea: when I call the logger.append() method, it just works fine, but when I use System.out.println(), all my French accents are lost.

Here, you have the creation of the logger and the redirection of System.out and System.err to it.

this.logger = new TextAreaOutputStream(jta, jsp.getVerticalScrollBar());
System.setProperty("user.langage", "fr");
PrintStream ps;
ps = new PrintStream(this.logger, true, "UTF-8");
System.setOut(ps);
System.setErr(ps);

Here, you have the TextAreaOutputStream class.

import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JScrollBar;
import javax.swing.JTextArea;

public class TextAreaOutputStream extends OutputStream {
    private JTextArea jta;
    private JScrollBar jsb;

    public TextAreaOutputStream(JTextArea jta, JScrollBar jsb) {
        this.jta = jta;
        this.jsb = jsb;
    }

    public synchronized void append(String s) {
        this.jta.append(s);
        scroll();
    }

    public synchronized void write(int b) throws IOException {
        jta.append(String.valueOf((char) b));
        if (((char) b) == '\n')
            scroll();
    }

    private synchronized void scroll() {
        if ((jsb.getValue() + jsb.getVisibleAmount()) == jsb.getMaximum()) 
            jta.setCaretPosition(jta.getDocument().getLength());
    }
}

I tried to change the encoding of the PrintStream to random encodings, it changed the look of the misprinted accents, but I never could have it right. I also tried to change the accents with unicode entries such as \u00e9 for é, but it did not change anything.

Here, I'm desperate enough to ask for your help,

Romain

¿Fue útil?

Solución

Your implementation of OutputStream is wrong: you pretend that write(int) receives characters, but in fact it receives raw bytes. If you check out PrintStream, you'll see that its print and append methods first apply encoding and then eventually call write(int) for each encoded byte.

You shoud not attempt to transfer raw bytes back to the string in your TextArea. Instead implement PrintStream and its character-based methods and shove those strings/char arrays directly into the UI component.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top