简体   繁体   中英

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.

You want a KeyListener, not an ActionListener.

Implement KeyListener, and then in the method keyPressed(KeyEvent name), type e.getKeyCode using either a switch or if statement. eg(pseudo code):

 javax.swing.JTextField input=null;
 javax.swing.JPanel panel=null;
 public class X implements java.awt.event.KeyListener{

 input = new javax.swing.JTextField();
 input.setBounds(10, 150, 780, 35);

 panel.add(input);
 input.addActionListener(new ActionListener());
 input.addKeyListener(this);
 public void keyPressed(java.awt.event.KeyEvent e){
 if(e.getKeyCode==e.VK_W){
 //Enter code here 
 }}public void actionPerformed(ActionEvent e) {
 //then upon enter the timer stops
 }


 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM