How to make scanner and keyListener cooperate with themselves?

I'm trying to create a program similar to Linux/Win terminal. I'm stuck because i want to create sth like command history. I'm using Scanner to read an input but while it's waitng for input KeyListener doesn't respond. So my question is "How to make keyListener and Scanner cooperate with each other ?"

public class main {

public static void main(String[] args) {
    KeyListener key = new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("tutej.");
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("test.");
        }
    };
    Scanner scan = new Scanner(System.in);
    while(true) {
        System.out.println("Write sth :");
        scan.nextLine();
    }


}

}