Simple Swing stdin/stdout console for command-line programs

Y

yay_frogs

I'd like to be able to run simple command-line programs that only use
standard input and output within Swing (or even AWT) so that
command-line programs can be run in either an applet or via Java Web
Start. I found online a simple way to redirect standard output to a
Swing JTextArea:

http://www.codecomments.com/message188868.html

However, this doesn't provide a way to redirect text typed into the
JTextArea to be redirected to standard input, which seems to be a
trickier problem and more work.

So before I reinvent the wheel and spend time figuring out the easiest
way to get characters typed in a JTextArea redirected to standard
input, has anyone done this before? (It seems like the sort of thing
someone must have done before.)

If no one knows of any existing implementation, then I'll probably
start by trying to go with the same approach used with the link above.
Here's code from the link above which shows how to define and then use
a DocumentOutputStream class which extends OutputStream:

/*
// Use the below DocumentOutputStream class like this:


private PrintStream redirectOutput(final JTextArea textarea) {
Document doc = textarea.getDocument();
// make the text area scroll automatically
doc.addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
textarea.setCaretPosition(e.getOffset());
}
public void insertUpdate(DocumentEvent e) {
textarea.setCaretPosition(e.getOffset());
}
public void removeUpdate(DocumentEvent e) {}
});
return new PrintStream(new DocumentOutputStream(doc));
}

*/

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

import java.util.*;


public class DocumentOutputStream extends OutputStream {

private Document _doc;

/** Creates a new instance of DocumentOutputStream */
public DocumentOutputStream(Document doc) {
if (doc == null) {
throw new NullPointerException("Cannot pass a null document to this
constructor");
}
_doc = doc;
}

public void write(byte[] buf, int offset, int length)
throws IOException {
try {
_doc.insertString(_doc.getLength(),
new String(buf, offset, length),
null);
} catch (BadLocationException ble) {
throw new IOException("Document append failed : " + ble);
}
}

public void write(int b) throws IOException {
try {
_doc.insertString(_doc.getLength(),
new String(new byte[] {(byte) b}),
null);
} catch (BadLocationException ble) {
throw new IOException("Document append failed : " + ble);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top