📄 listenerdemo.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -