KeyStroke/KeyPress in Java
Submitted by donbermoy on Wednesday, December 17, 2014 - 00:22.
Language
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:
3. We will initialize variables in our Main, variable frame as JFrame, button as JButton, and ACTION_KEY as String.
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:
6. Lastly, add the button, set the size, visibility, and the close operation of the frame. Have this code below:
Output:
Here's the full code of this tutorial:
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
- 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
4. Create an ActionEvent to your button and will print "The spacebar button is pressed!". Have this code below:
- }
- };
- inputMap.put(space, ACTION_KEY);
- actionMap.put(ACTION_KEY, actionListener);
- button.setActionMap(actionMap);
- frame.getContentPane().add(button);
- frame.setSize(400, 200);
- frame.setVisible(true);
- 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 {
- }
- };
- inputMap.put(space, ACTION_KEY);
- actionMap.put(ACTION_KEY, actionListener);
- button.setActionMap(actionMap);
- frame.getContentPane().add(button);
- frame.setSize(400, 200);
- frame.setVisible(true);
- }
- }
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.
Add new comment
- 493 views