How to Execute a KeyEvents ONCE ???

I’m making a game, and I want to make the executions triggered by a key event to only happen ONCE when you hold down the button. I want to obligated the user to press the Button Again to activate It’s function. In other words I want to take off rapid fire.

I made a simple frame that will print a sentence telling you how many times it has executed in the console when you press “Enter”. The source code is below, and I will Appreciate if anyone can tell me how to disable the rapid fire.

import javax.swing.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class KeyEventExecuteOnce implements KeyListener {

public static int X = 0;

public void keyPressed(KeyEvent Event) {

	switch (Event.getKeyCode()) {

	case KeyEvent.VK_ENTER:
		System.out.println("Button was Pressed " + X++ + " times");
		break;

	}

}

public void keyReleased(KeyEvent Event) {

}

public void keyTyped(KeyEvent Event) {

}

public static void main(String[] args) {

	JFrame frame = new JFrame("Execute Key Event once per button press ");
	KeyEventExecuteOnce KeyBoard = new KeyEventExecuteOnce();
	JLabel Label = new JLabel("Press Enter to print to the Console");

	frame.setSize(210, 100);
	frame.setLocationRelativeTo(null);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setVisible(true);
	frame.setFocusable(true);
	frame.addKeyListener(KeyBoard);
	frame.add(Label);
}

}

Put a flag in;


import javax.swing.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class KeyEventExecuteOnce implements KeyListener {

	public static int X = 0;
        public static boolean enterKeyHasBeenPressed=false;

	public void keyPressed(KeyEvent Event) {

  		switch (Event.getKeyCode()) {

		case KeyEvent.VK_ENTER:
                        if (!enterKeyHasBeenPressed)
                        {
			        System.out.println("Button was Pressed " + X++ + " times");
                                enterKeyHasBeenPressed=true;
                        }
 			break;
		}
	}

	public void keyReleased(KeyEvent Event) {
  		switch (Event.getKeyCode()) {

		case KeyEvent.VK_ENTER:
                        enterKeyHasBeenPressed=false;
 			break;
		}
	}

	public void keyTyped(KeyEvent Event) {

	}

	public static void main(String[] args) {

		JFrame frame = new JFrame("Execute Key Event once per button press ");
		KeyEventExecuteOnce KeyBoard = new KeyEventExecuteOnce();
		JLabel Label = new JLabel("Press Enter to print to the Console");

		frame.setSize(210, 100);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		frame.setFocusable(true);
		frame.addKeyListener(KeyBoard);
		frame.add(Label);
	}

}

WOW, Thanks Man. 8)

Didn’t you ask this on GameDev.net? I answered you there.

I’ve never been to that website. You have me mistaken.

Ok, sorry. It’s just that the question was identical. ;D