This problem usually occurs with focus on the panel, every time you are pressing any key you have to make sure the panel is in focus.
You'll want to look at the Java Tutorial for a good overview of Key Bindings as @camickr mentioned it in the comment.
Also look at question answered by @mKorbel (very interested answer).
The interested thing in Key Bindings is: say when you press on Ctrl+Shift+Space the program do some operation, it's very interesting and highly recommended to use Key Bindings, also see my first question on stack was about this subject.
This your code I'v made some changes :
KeyListener
every time presses a key the focus will be on the panel.MouseListener
When mouse enters on the panel or when a mouse clicks on the panel, again the focus will be on the panel.FocusListener
: to know either the panel is focusable or not.
Here is the code :
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class MovingJPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("Frogger");
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setSize(400,400);
JPanel abc = new JPanel();
abc.setBackground(Color.CYAN);
abc.getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "left");
abc.getActionMap().put("left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("LEFT");}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "right");
abc.getActionMap().put("right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("ROIGHT");}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("UP"), "up");
abc.getActionMap().put("up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("UP");}
});
abc.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "down");
abc.getActionMap().put("down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("DOWN");}
});
abc.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
System.out.println("Focus Gained");
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("Focus Lost");
}
});
abc.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
JPanel p = (JPanel)e.getSource();
p.requestFocus();
}
});
abc.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
JPanel p = (JPanel)e.getSource();
p.requestFocus();
}
});
frame.getContentPane().add(abc,"Center");
frame.getContentPane().add(new JButton("Click Me"),"North");
abc.requestFocusInWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}