listenerdemo.java

来自「JAVA的一些基础教程」· Java 代码 · 共 54 行

JAVA
54
字号
import java.awt.*;
import java.awt.event.*;

//定义一个类继承WindowAdapter并实现ActionListener接口
public class ListenerDemo extends WindowAdapter implements ActionListener
{
	Frame win;
	TextArea t;
	Button b;
	Button c;
	public ListenerDemo()
	{
		win = new Frame("my first GUI application");
		t = new TextArea("textfield");	
		t.setBackground(Color.red);
		b = new Button("ok");
		//因为当前对象实现了ActionListener接口,所以可以做为按钮事件的处理对象
		b.addActionListener(this);
		
		//将同一事件处理代理对象,添加两次
		b.addActionListener(this);

		c = new Button("clear");

		//按钮C也同样用当前对象来处理
		c.addActionListener(this);
		
		//当前类继承了WindowAdapter类,所以可以处理Window事件
		win.addWindowListener(this);

		win.add("Center",t);
		win.add("East",b);
		win.add("West",c);
		win.pack();
		win.show();
	}
	public void windowClosing(WindowEvent e)
	{
		System.exit(0);
	}
	public void actionPerformed(ActionEvent e) 
		{
			//获取按钮的事件源,查看事件的哪个对象产生的
			if(e.getSource() == b)
				t.append("hello\n");
			if(e.getSource() == c)
				t.setText("");
			}
	public static void main(String arg[])
		{
		new AwtDemo5();
		}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?