您可以使用 Robot 类来实现您想要的。例如,尝试以下操作:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Scanner;
public class RobotText {
static private Robot robot;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter some text, blank line to end.");
int count = 1;
while (true) {
System.out.print("?>");
insert("Line " + count);
count++;
String line = input.nextLine();
if (line.length() == 0) break;
System.out.println("You entered '" + line + "'");
}
System.out.println("That's all folks!");
input.close();
}
private static void insert(String text) {
if (robot == null) {
// Lazily initialise the robot
try {
robot = new Robot();
robot.setAutoDelay(5);
robot.setAutoWaitForIdle(true);
} catch (AWTException e) {
e.printStackTrace();
}
}
char[] chars = text.toCharArray();
for (char c : chars) {
int code = KeyEvent.getExtendedKeyCodeForChar(c);
robot.keyPress(code);
robot.keyRelease(code);
}
}
}
这会在使用扫描仪读取结果行之前插入您希望用户作为击键编辑的文本。注意 - 不要插入换行符,否则用户将永远没有机会输入!
不幸的是,您仍将受制于运行应用程序的 shell 提供的任何行编辑功能。在我的情况下,这意味着用户可以对上述内容进行的所有操作都是在重新输入替换之前根据需要在预先输入的文本上退格。
为避免这种情况,您需要将 Scanner 的使用替换为更复杂的东西。我还没有尝试过,但看起来JLine 可以满足您的需求。
对于极端的过度杀伤,在可以运行 GUI 的环境中,或者如果由于某种原因您无法将新 jars 添加到类路径中,您也可以使用 JOptionPane 进行输入:
...
while (true) {
String line = JOptionPane.showInputDialog("Enter some text","Line "+count);
count++;
if (line == null || line.length() == 0) break;
System.out.println("You entered '" + line + "'");
}
...
这确实为每一行输入启动了一个新的 Swing Event 线程,然后再次将其关闭,所以它确实是在使用大炮杀死苍蝇!但当然它要求在控制台的单独窗口中输入,这可能与您的目标相差太远。
最终的答案是为您的应用程序提供一个图形界面,因为我遇到的每个工具包提供的每个文本输入小部件都允许您使用随后可以由用户编辑的文本来预初始化小部件。我将把工具包的选择和实现留给读者作为练习。 :)