📜  Java ActionListener接口

📅  最后修改于: 2020-09-29 01:21:31             🧑  作者: Mango

Java ActionListener接口

每当您单击按钮或菜单项时,都会通知Java ActionListener。根据ActionEvent通知它。可在java.awt.event包中找到ActionListener接口。它只有一种方法:actionPerformed()。

actionPerformed()方法

每当您单击注册的组件时,都会自动调用actionPerformed()方法。

public abstract void actionPerformed(ActionEvent e);

如何编写ActionListener

常见的方法是实现ActionListener。如果实现ActionListener类,则需要遵循3个步骤:

1)在类中实现ActionListener接口:

public class ActionListenerExample Implements ActionListener

2)向侦听器注册组件:

component.addActionListener(instanceOfListenerclass);

3)覆盖actionPerformed()方法:

public void actionPerformed(ActionEvent e){
            //Write the code here
}

Java ActionListener示例:在“按钮”上单击

import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
    //2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
            tf.setText("Welcome to Javatpoint.");
}
}

输出:

Java ActionListener示例:使用匿名类

我们还可以使用匿名类来实现ActionListener。这是简写方式,因此您无需执行以下3个步骤:

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
            tf.setText("Welcome to Javatpoint.");
}
});

让我们使用匿名类查看ActionListener的完整代码。

import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
            tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

输出: