- <p>import java.awt.Graphics;
- import java.awt.event.KeyAdapter;
- import
- java.awt.event.KeyEvent;</p>
- <p>import javax.swing.JFrame;
- import javax.swing.JPanel;</p>
- <p>public class MyPanel extends JPanel
- {
- int x = 12, y = 22;
-
- MyPanel()
- {
- this.addKeyListener(new KeyAdapter()
- {
- public void keyPressed(KeyEvent e)
- {
- int code = e.getKeyCode();
- switch(code)
- {
- case KeyEvent.VK_UP:add();//在这里调用了add()方法但不响应?
- }
- }
- });
- }
-
- public void paint(Graphics g)
- {
- g.drawString("MyPanel",x,y);
- }
-
- public void add()
-
- {
- x++;
- y++;
- repaint();
-
- }
- public static void main(String[] args)
- {
- //
- TODO Auto-generated method stub
- JFrame f = new
- JFrame();
- f.setBounds(1, 2, 300,
- 300);
- f.setVisible(true);
- f.add(new
- MyPanel());
-
- }</p>
- <p>}</p>
复制代码 如何在JPanel中实现键盘事件?
|