2
私はSystem.in
にユーザ入力を指示してJTextArea
のコンソールをシミュレートしようとしています。テスト文字列はJTextArea
に正常に追加され、メインメソッドのScanner.nextLine()
は正常にユーザー入力を待ち、印刷します。ボタンを押しても、同じappendメソッドとscannerメソッドは機能しません。どんな勧告?ありがとう。スキャナがActionListenerで動作しません
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;
}
}
私はスキャナがGUIではなくコマンドラインツールだと思います。 _button_が押されたときにスキャナが次の行をキャプチャさせる原因となると思われるものは何ですか? –
'新しいScanner(System.in);'はコマンドラインからの入力を受け取ります。 GUIアプリケーションでは、このようなコマンドラインを使用することは保証されていません –
Enterキーを押すとPipedInputStreamからSystem.inに入力が進み、スキャナはSystem.inからその情報を取得するため、右? –