Search code examples
javaswingawtactionlistenerjtextfield

Adding ActionListener for a typing game


Have been looking at lots of documents about use of ActionListener with JTextField and have seen a lot of the other questions asked for similar reasons, but I cant seem to apply the solutions to my problem. The basic premise of what I need is there will be a text field on the screen for the user to type words into.

I want a timer to start running in the background after a certain key press. (preferably enter or spacebar) and then the timer should stop when the entire sentence has been written. So far I have not had much luck with getting an event to start with a key press. Below is some code that doesn't really work, I can successfully create the frame with the text box I just can't get the action listener to work for the purpose I want it for.

input = new JTextField();
input.setBounds(10, 150, 780, 35);
panel.add(input);
input.addActionListener(new ActionListener());

public void actionPerformed(ActionEvent e) {
}

Haven't added anything in the actionPerformed method as all the tests I ran weren't successful. Not asking for full code but a pointer in the right direction could help. Yes I have read the docs on how to use addActionListener() but I can't apply it to what I want to do.


Solution

  • You want a KeyListener, not an ActionListener.