在这个并非尽善尽美的世界上,勤奋会得到报偿,而游手好闲则要受到惩罚。——毛姆
本讲内容:MouseEvent 、MouseMotionListener
一、MouseEvent 让鼠标能知道鼠标按下的消息、知道点击的位置等五个方法。
MouseMotionListener鼠标拖动坐标、鼠标移动坐标二个方法。
public class Text extends JFrame {
MyPanel mb=null;
public static void main(String[] args) {
Text t=new Text();//每定义一个 t 都会产生一个对应的this
}
public Text() {
mb=new MyPanel();
this.addMouseListener(mb);//添加监听
this.addMouseMotionListener(mb);
this.add(mb);
//设置窗体属性
this.setTitle("技术大牛—小劲");
this.setLocation(300, 300);
this.setSize(400,400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements MouseListener,MouseMotionListener{
public void paint(Graphics g) {
super.paint(g);
}
//MouseListener 接口方法
//鼠标被点击(鼠标按下然后松开后执行)
public void mouseClicked(MouseEvent e) {
System.out.println("鼠标点击了 x="+e.getX()+"y="+e.getY());
}
//鼠标移动到MyPanel
public void mouseEntered(MouseEvent e) {
System.out.println("鼠标移动到MyPanel");
}
//鼠标离开MyPanel
public void mouseExited(MouseEvent e) {
System.out.println("鼠标离开MyPanel");
}
//鼠标按下
public void mousePressed(MouseEvent e) {
System.out.println("鼠标按下");
}
//鼠标松开
public void mouseReleased(MouseEvent e) {
System.out.println("鼠标松开");
}
//MouseMotionListener 接口方法
//鼠标拖动
public void mouseDragged(MouseEvent e) {
System.out.println("鼠标拖拽的当前坐标 x="+e.getX()+"y="+e.getY());
}
//鼠标移动
public void mouseMoved(MouseEvent e) {
System.out.println("鼠标当前坐标 x="+e.getX()+"y="+e.getY());
}
}二、KeyListener 键盘事件有三个方法。WindowListener 窗口事件有七个方法。
public class Text extends JFrame {
MyPanel mb=null;
public static void main(String[] args) {
Text t=new Text();
}
public Text() {
mb=new MyPanel();
this.addKeyListener(mb);
this.addWindowListener(mb);
this.add(mb);
//设置窗体属性
this.setTitle("技术大牛—小劲");
this.setLocation(300, 300);
this.setSize(400,400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements KeyListener,WindowListener{
public void paint(Graphics g) {
super.paint(g);
}
//键被按下
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar()+"键被按下了");//e.getKeyCode()是ASCII码
}
//键被释放
public void keyReleased(KeyEvent e) {
}
//键的一个值被打印输出(上下左右键等不会执行,因为没打印出)
public void keyTyped(KeyEvent e) {
}
//窗口激活了(窗口还原后即激活)
public void windowActivated(WindowEvent e) {
System.out.println("窗口激活了");
}
//窗口关闭
public void windowClosed(WindowEvent e) {//很少用到
System.out.println("窗口关闭");
}
//窗口正在关闭
public void windowClosing(WindowEvent e) {
System.out.println("窗口正在关闭");
}
//窗口失去激活(窗口最小化)
public void windowDeactivated(WindowEvent e) {
System.out.println("窗口失去激活");
}
//窗口还原
public void windowDeiconified(WindowEvent e) {
System.out.println("窗口还原");
}
//窗口最小化
public void windowIconified(WindowEvent e) {
System.out.println("窗口最小化");
}
//窗口打开
public void windowOpened(WindowEvent e) {
System.out.println("窗口打开");
}
}
原文:http://blog.csdn.net/liguojin1230/article/details/42490809