-1

I managed to get the user keystrokes and store it in an arrayList of type character. the only problem I have that when the user type something outside the JTextArea I wont be able to get the keystrokes any more. so is there a way of getting the keystrokes even if the user using Microsoft work for instance not the JTextArea.

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Sadasd extends JFrame {

    private JTextField userText;
    private JTextArea chatWindow;
     ArrayList<Character> stringList;
    public Sadasd(String host){
        super(" mofo!");
         stringList = new ArrayList<Character>();
        userText = new JTextField();
        userText.setEditable(false);
        userText.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    userText.setText("");
                }
            }
        );

        add(userText, BorderLayout.NORTH);
        chatWindow = new JTextArea();
        add(new JScrollPane(chatWindow), BorderLayout.CENTER);
        setSize(300,150);
        setVisible(true);
    chatWindow.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
       //  System.out.println(e.getKeyChar());
         stringList.add(e.getKeyChar());
        System.out.println(stringList);
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {

    }
} );
    }
}
TEK
  • 1,265
  • 1
  • 15
  • 30
johan
  • 39
  • 1
  • 7

2 Answers2

0

Actually it is not possible without using any library.

You might want to check JNativeHook which will do all the hard works for you.

Here an example pasted from the link I gave you :

public class GlobalKeyListenerExample implements NativeKeyListener {
    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
            GlobalScreen.unregisterNativeHook();
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }    
}

To accomplish this task, JNativeHook leverages platform-dependent native code through Java's native interface to create low-level, system-wide hooks and deliver those events to your application.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
0

Java does not provide a way to, with standard libraries, fetch keystrokes outside any windows your program owns.

The Java Native Access library (and others) provide a way to do this.
If you're searching for a simpler library, you may prefer JIntellitype.