How can I add keyboard shortcuts to a Java applet?
I had an assignment (I am taking Honors Computer Science) to make my name spin in a circle. I used an infinite loop, and every time I want to end, I have to go to Task Manager and end the program. Can I add a shortcut that quits the applet?
For example, if I press the space bar, it will change to another part of the program.
I looked over "How to Use Key Bindings" at Oracle's website but I could not understand it.
If you are using Swing (if you are creating a JApplet), then yes, Key Bindings are the way to go. What about them confuses you?
By the way, I know that this isn't directly related to your question, but if your applet is a Swing JApplet, I wouldn't use an infinite loop to do the animation, but rather I'd use a Swing Timer. If you use an infinite loop, you must take care to a) do the infinite loop in a background thread, and b) make most Swing calls from within the loop on the Swing event dispatch thread (or EDT) else you risk freezing the main Swing thread. A Swing Timer does all of this for you, and is thus much easier to use.
All that tutorial is saying that you need a KeyStroke
, some key Object
, and an Action
to create a key binding.
To create your KeyStroke
, take a look at the static helper methods , they should explain how to get the correct KeyStroke
you need.
You can use any old Object
as the key ( Object key = new Object()
).
The last thing you need is to create your Action
. I would suggest extending AbstractAction
since it already implements many of the methods of Action
for you.
To put your key binding together do the following:
JComponent c = ...
KeyStroke keyStroke = ...
Object key = ...
Action a = ...
c.getInputMap().put(keyStroke, key);
c.getActionMap().put(key, a);
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.