Because I thanked my game for using the keyboard to control the movements of planes, I used the keyboard to listen to events. However, after using the jpanel, I added the keyboard listening events, the plane did not respond by pressing the corresponding arrow keys. However, if it is for the jframe content panel, there will be a response.
To enable the use of Keyboard Events in jpanel, the solution is as follows:
1. Add a keyboard listener to the jpanel.
This. addkeylistener (New keyadapter (){
Public void keypressed (keyevent e ){
Switch (E. getkeycode ()){
Case keyevent. vk_up:
Player. Move ("up ");
Break;
Case keyevent. vk_down:
Player. Move ("down ");
Break;
Case keyevent. vk_right:
Player. Move ("right ");
Break;
Case keyevent. vk_left:
Player. Move ("Left ");
Break;
Case keyevent. vk_z: // Z used missiles to blow up all enemy planes
Player. usemissile (enemyplanes, bombs );
Break;
}
}
});
2. Set the jpnael to be added as a static member in the main function.
Private Static backgroundpanel panelbackground;
3. initialize static members in the jframe constructor and add them to the content Panel. In the main function, make the jpanel focus.
In the frame constructor:
Panelbackground = new backgroundpanel ();
Panelbackground. setbounds (0, 0, 386,385 );
Contentpane. Add (panelbackground );
In the main function:
Gameframe frame = new gameframe ();
Frame. setvisible (true );
Gameframe. panelbackground. requestfocus ();
Add keyboard listening events in jpanel