AWT事件监听作业学习例子(4) - KeyEvent
【事件执行情况】组件中发生击键时执行。 【传递的接口名】KeyListener 【需要实现方法】keyPressed - 按下某个键时调用此方法;keyReleased - 释放某个键时调用此方法;keyTyped - 键入某个键时调用此方法 【样例】按下上下左右方向时移动矩形/显示键入的键(非上下左右时) |
-
import javax.swing.*;
-
import java.awt.*;
-
import java.awt.event.*;
-
-
public class CallByKey {
-
-
/**
-
* @author Linyq.
-
*/
-
MyFrame frm = new MyFrame();
-
}
-
-
}
-
-
-
public MyFrame(){
-
this.setTitle("KeyEvent 测试");
-
this.setSize(260,240);
-
-
label.setLayout(null);
-
this.getContentPane().add(label,"North");
-
-
final DrawPanel panel = new DrawPanel();
-
panel.setSize(200,200);
-
this.getContentPane().add(panel,"Center");
-
-
// 用于接收键盘事件(击键)的侦听器接口。
-
-
// 按下某个键时调用此方法
-
panel.moveItem(0,-10);
-
}
-
panel.moveItem(0,10);
-
}
-
panel.moveItem(-10,0);
-
}
-
panel.moveItem(10,0);
-
}
-
}
-
-
// 释放某个键时调用此方法
-
label.setText("释放了刚刚按下的键");
-
}
-
-
// 键入某个键时调用此方法
-
label.setText("刚刚键入了"+e.getKeyChar() + "键");
-
}
-
-
});
-
-
this.setVisible(true);
-
}
-
-
}
-
-
-
private int x = 120;
-
private int lx = x;
-
private int y = 80;
-
private int ly = y;
-
private int w = 10;
-
private int h = 10;
-
-
super.paintChildren(g);
-
g.clearRect(lx-1, ly-1, w+2, h+2);
-
g.drawRect(x,y,w,h);
-
this.lx = this.x;
-
this.ly = this.y;
-
}
-
-
public void moveItem(int x,int y){
-
this.x += x;
-
if(this.x>240) this.x = 0;
-
if(this.x<0) this.x = 240;
-
this.y += y;
-
if(this.y>175) this.y = 0;
-
if(this.y<0) this.y = 175;
-
repaint();
-
}
-
-
}