您的位置:首页 > 编程语言 > Java开发

java事件处理总结

2014-12-03 21:28 417 查看
  
JAVA事件无非就是键盘事件,鼠标事件,按钮等事件。专业点可以分为语义事件(按钮等到事件)和低层事件(键盘事件,鼠标事件);

下面我简要的总结一下:

 1、鼠标事件:点鼠标按钮事它会调用三个监听器方法:mousePressed,mouseReleased,mouseClicked.

鼠标事件提供了mousePressed,mouseClicked,mouseDragged,mouseEntered,mouseExited, mouseUp,mouseDown,mouseDrag等事件。下面介绍一个鼠标一例子:

import java.awt.*;

import java.applet.Applet;

public class CountClick extends Applet

{int CurrentMarks=0;

int a,b;

 public boolean mouseDown(Event evt,int x,int y)//鼠标按下时做的事

 { CurrentMarks++;//计录按下次数

   repaint();//刷新面版

   a=x;//得到鼠标的横坐标

   b=y;//得到鼠标的竖坐标

   return true;

 }

 public void paint(Graphics g)

 { g.drawString(" "+CurrentMarks,10,10);//打印按下次数

   g.drawString(" "+a,10,30);//打印鼠标的横坐标

   g.drawString(" "+b,10,20);//打印鼠标的坚坐标

 }

}

//<applet code="CountClick.class" width="200" height="100"></applet>            

   2、键盘事件:如果我们希望使用键盘获得输入信息,就必须处理键盘事件。我们可以用在Conponent的keyDown来实现。如下例子:

import java.applet.Applet;import java.awt.*;

{   char Presskey;

     public boolean keyDown(Event evt, int key)

     {   Presskey=(char)key;//记录你按下的键

     repaint(); return true;

}

      public void paint(Graphics g)

     {    g.drawString(Presskey,10,10); }//打印你按下的键值

}

   3、铵钮等事件:这方面的内容比较多,通过一个例子做一个简单的介绍。

//

///

import java.awt.*;

import java.applet.Applet;

import java.awt.event.*;

public class Awtactiontest2 extends Applet implements ItemListener ,ActionListener

//实现ItemListener ,ActionListener接口

{

 int num = 5;

  Choice ch=new Choice ();

 Button one=new Button("one");

 Button two=new Button("two"); 

 Button three=new Button("three");

 Image  aa[];

 Image  a;

 public void init()

 {

        aa = new Image[num];

        for(int i = 0; i < num; i++)//把图片的路径加到数组中存储

        {

            aa[i] = getImage(getdocument.ase(),"A"+(i+1)+".JPG");

        }

        num=4;//给一个初值

 this.setBackground(Color.white);

 ch. addItem("A1.JPG" );

 ch. addItem ("A2.JPG" );

 ch. addItem ("A3.JPG" );

 ch. addItem ("A4.JPG" );

 add (ch);

 a = getImage(getdocument.ase(),"A1.JPG");//对a一个初值;

 add (one);

 add (two);

 add (three);

 ch.addItemListener(this);//注意把ItemListener接口implements进来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: