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

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

2013-01-20 15:07 429 查看


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

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐