第五十节 java学习——动作事件(ActionEvent)

来源:互联网 发布:数据恢复精灵使用教程 编辑:程序博客网 时间:2024/06/10 11:31

 

动作事件(ActionEvent)

 

ActionEvent包含一个事件,该事件为执行动作事件ACTION_PERFORMED.触发这个事件的动作为:
1》点击按钮。
2》双击列表中选项。
3》选择菜单项。
4》在文本框中输入回车。
常用方法如下:
public String getActionCommand()
返回引发某个事件的命令按钮的名字,如果名字为空,那么返回标签值。
public void setActionCommand(String command)
设置引发事件的按钮的名字,默认设置为按钮的标签。

 

程序例子:

 

//程序文件名Test.java
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Test extends Applet implements ActionListener {
 String str1=new String();
 Button b1;//声明按钮对象;
 Button b2;
 Color c;
 public void init() {
  b1=new Button();
  b2=new Button("按钮对象2");
  //添加事件监听者
  b1.addActionListener(this);
  b2.addActionListener(this);
  this.add(b1);
  this.add(b2);
 }
 public void start()
 {
  b1.setLabel("按钮对象1");
  str1=b2.getLabel();
  repaint();
 }
 public void paint(Graphics g) {
  g.setColor(c);
  g.drawString("引发事件的对象的标签:"+str1, 40, 60); 
 }
 //实现接口中的方法,响应动作事件
 public void actionperformed(ActionEvent e) {
  String arg=e.getActionCommand();
  if(arg=="按钮对象1"){
   c=Color.red;
   str1="按钮对象1";
    }
  else if(arg=="按钮对象2"){
   c=Color.blue;
   str1="按钮对象2";   
  }
  repaint();
 }
 
 
}

原创粉丝点击