模拟java.util.Scanner的用户输入 [英] Emulating user input for java.util.Scanner

查看:169
本文介绍了模拟java.util.Scanner的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写游戏,我希望用户能够提供命令行和GUI的输入.当前,我使用此方法获取输入:

I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input:

    static String getInput(){
        System.out.println("Your move:");
        Scanner sc = new Scanner(System.in);
        return sc.nextLine();
    }

我想继续使用它,但是让mousePressed事件也可以模拟用户实际在其输入中输入的内容.解决方案的效率并不高,但是在我的应用程序中才有意义.所以问题是:我该如何模拟从代码端键入System.in的用户?

I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well. It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side?

推荐答案

这是可能的-用 PipedOutputStream 从另一个线程(在本例中为Swing线程)写入.

This is possible - the easiest substitution for System.in would be a PipedInputStream. This must be hooked up to a PipedOutputStream that writes from another thread (in this case, the Swing thread).

public class GameInput {

    private Scanner scanner;

    /**CLI constructor*/
    public GameInput() {
        scanner = new Scanner(System.in);
    }

    /**GUI constructor*/
    public GameInput(PipedOutputStream out) throws IOException {
        InputStream in = new PipedInputStream(out);
        scanner = new Scanner(in);
    }

    public String getInput() {
        return scanner.nextLine();
    }

    public static void main(String[] args) throws IOException {
        GameInput gameInput;

        PipedOutputStream output = new PipedOutputStream();
        final PrintWriter writer = new PrintWriter(output);
        gameInput = new GameInput(output);

        final JTextField textField = new JTextField(30);
        final JButton button = new JButton("OK");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String data = textField.getText();
                writer.println(data);
                writer.flush();
            }
        });

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(textField);
        frame.getContentPane().add(button);
        frame.pack();
        frame.setVisible(true);

        String data = gameInput.getInput();
        System.out.println("Input=" + data);
        System.exit(0);
    }

}

但是,最好重新考虑游戏逻辑,以便在GUI模式下完全切断流.

However, it might be better to rethink your game logic to cut out the streams altogether in GUI mode.

这篇关于模拟java.util.Scanner的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆