Java 在Swing 面板中添加 ActionLinsener监听器的几种方法
经过一段时间的对于Swing的学习,总结了一下两种对JButton控件添加ActionListener监听器的方法
方法一
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//定义监听器类
public class ActionListenerTest{
private JFrame jf;
private JButton jtn1;
private JPanel jp;
public static void main(String[] args){
jf=new JFrame("ActionListenerTest");
jp=new JPanel();
jtn1=new JButton("点击触发事件");
jtn1.addActionListener(new ActionListener(){
public void ActionPerform(ActionEvent e){
//TODO
}
});
jf.setSize(300,300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
}
}
方法二
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//定义监听器类
public class ActionListenerTest implements ActionListener{
private JFrame jf;
private JButton jtn1;
private JPanel jp;
public static void main(String[] args){
jf=new JFrame("ActionListenerTest");
jp=new JPanel();
jtn1=new JButton("点击触发事件");
jtn1.addActionListener(this);
jp.add(jtn1);
jf.add(jp);
jf.setSize(300,300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
}
public void ActionPerform(ActionEvent e){
//TODO
}
}