首先我们要知道动作监听器的源代码在:java.awt.event.ActionListener
我们可以在类之前导入包的路径:
import javax.swing.Jframe;
接口不是一个类,但与类同级。
接口的特点:
1.方法没有方法体:是说它后面没有大括号,没有具体实现的操作
2.没有属性变量,只有静态常量:
静态常量:不需要对象调用,直接又类名调用
它不属于对象,只属于类,且只有一份
3.可以声明,但不可以创建
格式:接口类型 接口变量名;
声明:ActionListener al;
不能创建对象,也就是ActionListener a=new ACtionListener()不可以这样创建;
下面是接口的使用步骤:
step1:创建一个类来实现接口。
用到implements。
import java.awt.event.ActionListener; //源代码要在最前面声明
public class ButtonAction implements ActionListener{
step 2:把接口中所有的抽象方法复制过来,去分号,改大括号。
public void actionPerformed(ActionEvent e){
step 3:在此处加上点击按钮之后需要执行的代码。例如:输出一句话、调用一个新的界面、执行一段新的代码等。
}
}
step 4 :与所需要监听的按钮或者菜单对象绑定:
1.创建这个类ButtonAction的对象
ButtonAction 对象名=new ButtonAction ();
2.使用组件对象调用addActionListener方法绑定这个对象
按钮对象名.addActionListener(对象名);
简单举个例子:
首先创建一个页面,这个上篇已经讲过方法了
在jf.setVisible(true); 下面加入监听器,代码如下:
import javax.swing.*;
import javax.swing.plaf.basic.BasicOptionPaneUI;
import java.awt.*;
public class My {
Color color = new Color(0,0,0);
public void showMy(){
Jframe jf =new Jframe();
jf.setTitle("登录页面");
jf.setSize(600,1000);
jf.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
FlowLayout fl=new FlowLayout();
jf.setLayout(fl);
JButton jbt = new JButton();
jbt.setText("登录");
jbt.setBackground(Color.PINK);
JTextField namein = new JTextField();
JPasswordField pwdin = new JPasswordField();
Dimension dim = new Dimension(500,50);
namein.setPreferredSize(dim);
pwdin.setPreferredSize(dim);
JLabel namejla = new JLabel("账号");
JLabel pwdjla = new JLabel("密码");
ImageIcon img = new ImageIcon("C:\Users\86139\Desktop\1234.jpg");
JLabel imgjla = new JLabel(img);
jf.add(imgjla);
jf.add(namein);
jf.add(namejla);
jf.add(pwdin);
jf.add(pwdjla);
jf.add(jbt);
jf.setVisible(true);
BtAction BAction =new BtAction();
jbt.addActionListener(BAction);
}
public static void main(String[] args) {
My me = new My();
me.showMy();
}
}
新建另一个包,文件名与类名一致,我这里是BtAction。代码如下:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BtAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了!");
}
}



