第2周:Java事件处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013899461/article/details/21322241

源程序1simpleEvent.java

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class simpleEvent extends Applet implements ActionListener  
{
    Label lb;
    TextField in,out;
    public void init()
    {
    	lb = new Label("请输入你的名字");
    	in = new TextField(6);        //创建输入文本框
    	out = new TextField(20);      //创建输出文本框
    	add(lb);
    	add(in);
    	add(out);
    	in.addActionListener(this);   //将文本框注册给文本事件的监听者
    }
    public void actionPerformed(ActionEvent e) //执行动作
    {
    	out.setText(in.getText() + "欢迎光临");
	}

}

运行结果:


源程序2ButtonDemo.java

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonDemo extends Applet implements ActionListener 
{ 
	String msg ="";
	public void init()
	{
		Button yes = new Button("是");
		Button no =new Button("否");
		Button maybe = new Button("取消");
	    add(yes);
	    add(no);
	    add(maybe);
	    yes.addActionListener(this);
	    no.addActionListener(this);
	    maybe.addActionListener(this);
	}
	public void actionPerformed(ActionEvent e)
	{
		String str = e.getActionCommand();
		if(str == "是")
		{
			msg = "你单击了按钮'是'。";
		}
		else if(str == "否")
		{
			msg = "你单击了按钮'否'。";	
		}
		else
		{
			msg = "你单击了按钮'取消'。";
		}
		repaint();
	    }
	public void paint(Graphics g)
	{
		g.drawString(msg,6,100);
	}

}

运行结果:


猜你喜欢

转载自blog.csdn.net/u013899461/article/details/21322241
今日推荐