I am in the process of playing with Jcrafts JSch Library to build a Terminal application.
It works fine and does what it says, however I have to redirect System out, in and err to various swing components for it work in a GUI application.
I have noticed with System.in redirection it relies on a keypress to submit the text to System.in, this is fine until you need to use CRTL keys for example. Also up arrow for previous commands.
Class for System.in redirection and KeyListener for submission
public class TextAreaStream extends InputStream implements KeyListener {
private JTextArea ta;
private String str = null;
private int pos = 0;
public TextAreaStream(JTextArea jtf) {
ta = jtf;
}
//gets triggered everytime that "Enter" is pressed on the textfield
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_ENTER)
{
str = ta.getText() + "\n";
pos = 0;
ta.setText("");
synchronized (this) {
this.notifyAll();
}
}
}
@Override
public int read() {
if(str != null && pos == str.length()){
str =null;
return java.io.StreamTokenizer.TT_EOF;
}
while (str == null || pos >= str.length()) {
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
return str.charAt(pos++);
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
My question is "Is there a way to have System.in recognize up arrows and CRTL- commands with JSch, or is there a better way of displaying a console screen in a Java Swing application?"
Implentation
//System input redirection from TextArea
TextAreaStream ts = new TextAreaStream(textAreaInput);
textAreaInput.addKeyListener(ts);
System.setIn(ts);