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

 

动作事件(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();
 }
 
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值