How do you _really_ get a PrintStream to flush all the time?



I create my own PrintStream directed to a JTextArea to act as a console for
a Swing application. I found an example of doing this online & implemented
away...

Unfortunately, writing to the console isn't at all deterministic. Messages
get trimmed. They are printed out of order, linefeeds don't happen.
Generally, it is a mess. And no end of flush() does any good at all...

Any suggestions are appreciated,

Rob

public class Console extends JPanel {
static PrintStream out;
private PipedInputStream piOut;
private PipedOutputStream poOut;
private JTextArea textArea = new JTextArea();

public Console() throws IOException {
piOut = new PipedInputStream();
poOut = new PipedOutputStream(piOut);
out = new PrintStream(poOut, true);
textArea.setEditable(false);
textArea.setRows(10);
textArea.setColumns(80);
add(new JScrollPane(textArea), BorderLayout.CENTER);
setVisible(true);
new ReaderThread(piOut).start();
}

class ReaderThread extends Thread {
PipedInputStream pi;
ReaderThread(PipedInputStream pi) {
this.pi = pi;
}
public void run() {
final byte[] buf = new byte[1024];
try {
while (true) {
final int len = pi.read(buf);
if (len == -1) {
break;
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(new String(buf, 0, len));
// Make sure the last line is always visible
textArea.setCaretPosition(textArea.getDocument().getLength());
// Keep the text area down to a certain character size
int idealSize = 10000;
int maxExcess = 5000;
int excess = textArea.getDocument().getLength() - idealSize;
if (excess >= maxExcess) {
textArea.replaceRange("", 0, excess);
}
}
});
}
} catch (IOException e) {
}
}
}
}


.



Relevant Pages

  • Re: How do you _really_ get a PrintStream to flush all the time?
    ... then I run the danger of overrunning the buffer (and maybe other ... I'm not sure whether to synchronize on the JTextArea or on the ... > I create my own PrintStream directed to a JTextArea to act as a console ... > public void run{ ...
    (comp.lang.java.help)
  • [PATCH 2.6] Altix serial driver
    ... patch for our console driver. ... We converted the driver to use the ... -static int sn_sal_is_asynch; ... -static void sn_sal_tasklet_action; ...
    (Linux-Kernel)
  • [PATCH 2.6] Altix serial driver
    ... patch for our console driver. ... We converted the driver to use the ... -static int sn_sal_is_asynch; ... -static void sn_sal_tasklet_action; ...
    (Linux-Kernel)
  • [patch] uml: terminal cleanup
    ... This is a major cleanup of the uml terminal drivers and console handling ... struct list_head *ele; ... int write_irq) ... void chan_interrupt(struct list_head *chans, struct work_struct *task, ...
    (Linux-Kernel)
  • [PATCH 8/8] kgdb: kgdboc 8250 I/O module
    ... console port. ... +#ifdef CONFIG_SERIAL_POLL ... static int serial8250_startup ...
    (Linux-Kernel)