I’m trying to simulate a console with a JTextArea
by directing user input to System.in
. The test string is successfully appended to the JTextArea
, and the main method’s Scanner.nextLine()
successfully waits for and prints user input. The same append and scanner methods don’t work when the button is pressed. Any recommendations? Thanks.
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class ScannerTest {
public static void main(String[] args) throws IOException {
PipedInputStream inPipe = new PipedInputStream();
System.setIn(inPipe);
PrintWriter inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
JTextArea console = console(inWriter);
Scanner sc = new Scanner(System.in);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
console.append("button pressed\n");
console.append("got from input: " + sc.nextLine() + "\n"); // cause of problem???
}
});
JFrame frame = new JFrame("Console");
frame.getContentPane().add(console);
frame.getContentPane().add(button, "South");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
console.append("test\n");
console.append("got from input: " + sc.nextLine() + "\n");
}
public static JTextArea console(final PrintWriter in) {
final JTextArea area = new JTextArea();
area.addKeyListener(new KeyAdapter() {
private StringBuffer line = new StringBuffer();
@Override public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (c == KeyEvent.VK_ENTER) {
in.println(line);
line.setLength(0);
} else if (c == KeyEvent.VK_BACK_SPACE) {
line.setLength(line.length() - 1);
} else if (!Character.isISOControl(c)) {
line.append(e.getKeyChar());
}
}
});
return area;
}
}
I think you overcomplicated things. Since you wanted a console, here I present a simpler solution to you. I don't recommend using
sc.nextLine()
in a context like yours due to bug they lead to. That might be cause of your problem, have a look at it. You can get input in various ways. For example:OR
Long story short, here's what I wrote. It might serve your purpose: