Home > Back-end > Which bosses to explain why the keyboard didn't listen to
Which bosses to explain why the keyboard didn't listen to
Time:09-26
The import javax.mail. Swing. JFrame; The import javax.mail. Swing. WindowConstants;
Public class GameFrame { Public static void main (String [] args) { JFrame j1=new JFrame (); J1. SetVisible (true); J1. SetBounds (100100570613); J1. SetDefaultCloseOperation (WindowConstants. EXIT_ON_CLOSE); J1. Add (new GamePanel ()); }
}
Import the Java. The awt. Event. KeyAdapter; Import the Java. The awt. Event. KeyEvent; The import javax.mail. Swing. JPanel;
Public class GamePanel extends JPanel { Public GamePanel () { Enclosing addKeyListener (new Listen ()); } The class Listen extends KeyAdapter { @ Override Public void keyPressed KeyEvent (e) { If (um participant etKeyCode ()==KeyEvent. VK_SPACE) { System. The out. Println (" press the blank space "); } } }}
CodePudding user response:
If not mistaken, you have to use anonymous inner class can solve, [KeyEvent anonymous inner class] baidu casually, gather together go to see https://blog.csdn.net/LeoZuosj/article/details/104230051 They could be a direction for check
CodePudding user response:
Because your GamePanel can't focus, a component to respond to events get focus first, otherwise the events of the components will only others are focusing on GamePanel rather than you, You can modify the main method GamePanel gp=new GamePanel (); J1. Add (gp);//can best j1 setLayout If (gp) isFocusable ()) { Gp. RequestFocuse ();//take the initiative to get focus }