This tutorial will teach you how to create a program in java that has a
KeyPress or
KeyStroke.
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of
keyStroke.java.
2. Import the following package library:
import java.awt.event.*; // used to access the ActionEvent clas
import javax.swing.*; //used to access the AbstractAction,Action,ActionMap,InputMap,JButton,JComponent,JFrame, and KeyStroke
3. We will initialize variables in our Main, variable
frame as JFrame,
button as JButton, and
ACTION_KEY as String.
String ACTION_KEY
= "theAction";
4. Create an ActionEvent to your button and will print
"The spacebar button is pressed!". Have this code below:
System.
out.
println("The spacebar button is pressed!"); }
};
5. To have a space keytroke used the KeyStroke class with the getKeyStroke class.
To provide an action on the button when pressing the spacebar, have this code below:
inputMap.put(space, ACTION_KEY);
actionMap.put(ACTION_KEY, actionListener);
button.setActionMap(actionMap);
6. Lastly, add the button, set the size, visibility, and the close operation of the frame. Have this code below:
frame.getContentPane().add(button);
frame.
setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE); frame.setSize(400, 200);
frame.setVisible(true);
Output:
Here's the full code of this tutorial:
import java.awt.event.*; // used to access the ActionEvent clas
import javax.swing.*; //used to access the AbstractAction,Action,ActionMap,InputMap,JButton,JComponent,JFrame, and KeyStroke
public class keyStroke {
public static void main
(String[] a
) {
String ACTION_KEY
= "theAction";
System.
out.
println("The spacebar button is pressed!"); }
};
inputMap.put(space, ACTION_KEY);
actionMap.put(ACTION_KEY, actionListener);
button.setActionMap(actionMap);
frame.getContentPane().add(button);
frame.
setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE); frame.setSize(400, 200);
frame.setVisible(true);
}
}
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
Mobile: 09488225971
Landline: 826-9296
E-mail:
[email protected]
Add and Follow me on Facebook:
https://www.facebook.com/donzzsky
Visit and like my page on Facebook at:
https://www.facebook.com/BermzISware
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.