Hello there Daniweb community, i am creating a 2d game in Java, however i have a problem. I googled up KeyListeners for JFrame, as they didnt work as usual, and i found out that when using KeyListeners with JFrame you have to set focus, right?

Well. I have Googled abit now, but cant seem to find a solution to my problem. If you guys could take a look at my codepiece, that would be a great help for me.

package com.amellingsen.erlend;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class BoxWorld extends JFrame implements KeyListener{

	public BoxWorld()
	{
		setFocusable(true);
		
		add(new Board());
		
		setTitle("BoxWorld");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(700, 700);
		setLocationRelativeTo(null);
		setVisible(true);
		setResizable(true);
		
		
	}
	
	public static void main(String[] args)
	{
		new BoxWorld();
	}

	public void keyPressed(KeyEvent e) {
		System.out.println("KeyPressed");
	}

	public void keyReleased(KeyEvent e) {
		System.out.println("KeyReleased");
	}

	public void keyTyped(KeyEvent e) {
		System.out.println("KeyTyped");
		
	}
	
}

Thanks in advance :)

This approach to keyboard handling is always a complete pain in the * because of precisely those focus issues.
Swing was enhanced back in Java 1.3 to provide a better way of doing things via two new classes: InputMap and ActionMap. Here's a good write-up on the theory behind it:
http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html#new_bindings
and this is the tutorial:
http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Edited 5 Years Ago by JamesCherrill: n/a

Thanks for the quick answer, sorry for not answering before now, have been at school (and im currently at work).

Ill check it out when i come home, but thanks :)

Cant seem to understand quite how to use those, ive been trying to follow some tutorials.

This is what i have ended up with, however i am abit stuck. (I dont know how to proceed from this point).

final InputMap ctrlMap = new InputMap();

private void loadctrls()
{
        ctrlMap.put(KeyStroke.getKeyStroke((KeyEvent.VK_UP), 0, false), "UP");
        ctrlMap.put(KeyStroke.getKeyStroke((KeyEvent.VK_DOWN), 0, false), "DOWN");
        ctrlMap.put(KeyStroke.getKeyStroke((KeyEvent.VK_LEFT), 0, false), "LEFT");
        ctrlMap.put(KeyStroke.getKeyStroke((KeyEvent.VK_RIGHT), 0, false), "RIGHT");
        
        super.setInputMap(0,  ctrlMap);
        
        System.out.println("Loaded controls.");
}

Any tips?

You don't necessarily need to create a new InputMap, you could use the existing for the component. Either way, you need to map the actions for those events now. That is what the action map is for. So for your "UP" action mapping you would have something like the following

board.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke((KeyEvent.VK_UP), 0, false), "UP");
board.getActionMap().put("UP",
     new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
                // Whatever you need to do on UP
                System.out.println("UP");
            }
        });

You don't necessarily need to create a new InputMap, you could use the existing for the component. Either way, you need to map the actions for those events now. That is what the action map is for. So for your "UP" action mapping you would have something like the following

board.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke((KeyEvent.VK_UP), 0, false), "UP");
board.getActionMap().put("UP",
     new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
                // Whatever you need to do on UP
                System.out.println("UP");
            }
        });

Thanks for your answer.
It seems like i cant refer to JComponent, or JFrame, or JPanel through the command?

In your actionPerformed(ActionEvent e) method you can use e.getSource() to return the object on which the Event initially occurred.

Thank you both for your answers, its really lovely to have a community with people like you!

I have managed to complete my code now, thanks to your answers. Really, thanks alot :)
(If you want me to publish my code, i will :) )

This question has already been answered. Start a new discussion instead.