views:

230

answers:

2

Hi, I have the following:

import javax.swing.JFrame;

public class Directions {

    public Directions(){
        JFrame frame = new JFrame("Direction");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DirectionPanel());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Directions myTest = new Directions();
    }
}

second class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DirectionPanel extends JPanel{
    public DirectionPanel(){
        addKeyListener(new DirectionListener());
        setBackground(Color.yellow);
    }

    private class DirectionListener implements KeyListener{

        @Override
        public void keyPressed(KeyEvent e) {
            //JOptionPane.showMessageDialog(null, "Hello Johnny");
            int keyCode = e.getKeyCode();
            if (keyCode == KeyEvent.VK_LEFT){
                setBackground(Color.red);
            }
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
        }
    }
}

Why doesn't the frame turn red when I hit the left arrow? I also had it with no keycode test thinking that no matter the key it would work but it did not. Thank you.

+5  A: 
public DirectionPanel(){
   addKeyListener(new DirectionListener());
   setFocusable(true);// INSERT THIS
   setBackground(Color.yellow);
}

JPanel needs to be focusable to receive KeyEvents

Erkan Haspulat
Reference: http://forums.sun.com/thread.jspa?threadID=5424784. (I was just about to answer the same thing.)
Michael Myers
Thanks for the reference..
Erkan Haspulat
+2  A: 

Swing components should use Key Bindings (not KeyListeners) for invoking an Action when the keyboard is used. A side benefit of this is that way you don't have to worry about focusability.

Action left = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println( "Left" );
    }
};

Object key1 = "left";
KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks1, key1);
panel.getActionMap().put(key1, left);
camickr