SAT SAT - 1 year ago 231
Java Question

How to use key binding with JFrame in java

I am trying to use key binding to control a game (up, down, left, right arrows). My plan is to use key binding with multi threading, calling some sort of an update method.

My code for the graphics window so far:

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Container;

public class Main extends JPanel{
public Main(){
JFrame window = new JFrame("New window");
window.setSize(300, 300);
Container c = window.getContentPane();
c.add(new Main());
public static void main(String[] args){
//some code
//multi threading code

I have read the documentation for key binding, but I am not sure how to use it for a JFrame. I think I should add it to c, but I am then not sure how to use the key binding. Thank you in advance for any help.

Answer Source

You need to use KeyBindings with a component that extends from JComponent, such as a JPanel as the object has to have the getActionMap() and getInputMap() to allow bindings to be made. JFrame does not extend from JComponent, and so you cannot directly bind to the JFrame, but can bind to any of its components that do satisfy this rule.

So, in your code above, you could add Key Bindings to the Main JPanel or to the JFrame's contentPane, which is a JPanel but will have to be cast as one first.

Your code above though has a problem in that the c.add(new Main()); in the Main's constructor will cause infinite recursion and thus a StackOverflowException. Either add this or put the JFrame creational code within the main method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download