I've read over your code several times, and nothing jumps out at me as not being correct. So I created a little launch program which creates a JFrame
with your custom JPanel
as the content pane ...
public class MoveRectangleArrowKeys {
public static void main(String[] args) {
SwingUtilities.invokeLater(MoveRectangleArrowKeys::new);
}
MoveRectangleArrowKeys() {
JFrame frame = new JFrame("Move Rectangle with Arrow Keys");
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Gameseeting());
frame.setVisible(true);
}
}
... and it works as expected.
So, the problem lies elsewhere. Either in the creation of the panel, or its interoperation with other code, or with its expected behaviour.
First, creation. Swing components should only ever be created on Swing's Event Dispatching Thread (EDT). If you are not using SwingUtilities.invokeAndWait(...)
or SwingUtilities.invokeLater(...)
when your main
method creates the application's UI, you could be putting Swing into a bad state.
Second, interoperation with other code. You've called setFocusable(true);
, which makes your component focusable. But if there is more than one focusable component in the frame, the focus may be taken by another UI element. Try a mouse click in your panel. If the rectangle begins responding to the arrow keys, then you may simply need to call requestFocusInWindow()
on your Gameseeting
panel after the frame has become visible.
Third, your expectations may be in error. If you are pressing the UP arrow on the numeric keypad, you may expect the rectangle to move in response to the VK_UP
code, but it won't. The code would need to test for the VK_NUMPAD8
code.
At any rate, the code as posted works. If you have simplified the code to post it on StackOverflow, you may have inadvertently removed the problem code. If you haven't simplified it, the problem is with other code in your project. If the above tips have not helped you, you will need to edit your post to add more information (and code) in order for us to replicate the problem and come up with a solution.
Remember to post a Minimal Complete Verifiable Example. Your posted code was not complete; I had to add the above launcher code to create and test your custom JPanel
. Since it does not demonstrate the problem, it is not a verifiable example. It may be that the launch code is problem, and it fails with your launch code, but not with mine. "Minimal" means removing all the unnecessary code that is not required to reproduce the problem. For example, you could remove the VK_UP
, VK_LEFT
, and VK_DOWN
code, leaving just the VK_RIGHT
code. That is a minimization, which could still leave the code "Complete". But removing the construction of the JPanel
does not leave you with a complete example. Test the code that you post, and make sure that it still demonstrates the problem; otherwise we can only guess at the real problem.