我建议您使用该SWT
工具包。
对于功能示例,请在下面运行我的代码。您只需要添加 SWT 依赖项。
写入控制台是愚蠢的。这更酷:
public class Waffles
{
// Keeps track of how many times any key is pressed
private static int keyCounter = 0;
// Used to continuously append characters from the input string
private final StringBuilder builder;
// This can be read from a file, or whatever
private final String GIBBERISH;
public static void main(final String[] args)
{
new Waffles();
}
private Waffles()
{
builder = new StringBuilder();
// Put your dummy code here (extract from a file)
GIBBERISH = " I freaking love waffles!";
// Loop the SWT Display
init();
}
private void init()
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("HackerTyper");
shell.setSize(500, 500);
shell.setLayout(new GridLayout());
shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Here we create the text area
createWidget(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private void createWidget(final Composite parent)
{
// Wrap it for multi line text, and set it to read only, so we can't modify
// the text 'manually'
final Text textArea = new Text(parent, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY);
textArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Yay colours!
textArea.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
textArea.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_GREEN));
// This is what was recommended by the other two answers
textArea.addKeyListener(new KeyListener()
{
@Override
public void keyPressed(final KeyEvent arg0)
{
// *magic*
textArea.setText( getGibberish() );
}
@Override
public void keyReleased(final KeyEvent arg0)
{
}
});
}
private String getGibberish()
{
if (keyCounter > GIBBERISH.length() - 1)
keyCounter = 0; // Careful not to go out of string bounds
// Continuously append it, then pass the whole text to the textArea
builder.append( GIBBERISH.charAt(keyCounter++) );
return builder.toString();
}
}
感觉像个黑客。像黑客一样。咻咻咻!我真的累了。