import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OuterClassEvent extends JFrame{
public OuterClassEvent(){
setLayout(new FlowLayout());
JButton btn=new JButton("ok");
add(btn);
OuterClass btListener=new OuterClass();
btn.addActionListener(btListener);
}
public static void main(String args[]){
OuterClassEvent frame = new OuterClassEvent();
frame.setTitle("外部类作为事件监听器");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 100);
frame.setVisible(true);
new ThisClassEvent();
}
}
class OuterClass implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("The OK button is clicked");
}
} 当btn.addActionListener(btListener)时为什么会输出The OK button is clicked
ActionListener接口明明要接受ActionEvent的引用.什么时候在那里传的
import java.awt.event.*;
import javax.swing.*;public class OuterClassEvent extends JFrame {
JButton btn;//为了看清楚怎么回事,把局部变量改为成员变量
public OuterClassEvent() {
setLayout(new FlowLayout());
btn = new JButton("ok");//为了看清楚怎么回事,把局部变量改为成员变量
add(btn);
/*
OuterClass btListener=new OuterClass();
btn.addActionListener(btListener);
*/
//等价于
/*
btn.addActionListener(new OuterClass());
*/ //等价于
/*
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The OK button is clicked");
}
});
*/
//等价于
/*
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The OK button is clicked");
JComponent jComponent = (JComponent) e.getSource();
if (jComponent instanceof JButton && btn == (JButton)jComponent){
//这里相当于按钮什么都没做,该做的在if之前已经做了,
//但是它既可以执行if之外的代码,也可以执行if子句的代码,试试看
}
}
});
*/
//等价于 btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComponent jComponent = (JComponent) e.getSource();
if (jComponent instanceof JButton && btn == (JButton)jComponent){
System.out.println("The OK button is clicked");//把代码写进来来,
//这里相当于按钮什么都没做,该做的在if之前已经做了,
//但是它既可以执行if之外的代码,也可以执行if子句的代码,试试看
}
}
});
} public static void main(String args[]) {
OuterClassEvent frame = new OuterClassEvent();
frame.setTitle("外部类作为事件监听器");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 100);
frame.setVisible(true);
// new ThisClassEvent();
}
}class OuterClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("The OK button is clicked");
}
}
但是它不是要接受ActionEvent类的参数吗?程序什么时候传参的?它是多态?像这种没有指明调用actionPerformed(接受对象类)方法的接口混淆了!!!
void jiao(String s);
}
class B implements moves{ @Override
public void jiao(String s) {
System.out.println(s);
}
public static void main(String[] args) {
String s=new String("ABCD");
moves m=new B();
m.jiao(s);
}
}接口调用不是要像这样要指明调用jiao()的!
addActionListener()里面没有调用actionPerformed()方法并且传值啊?
如果自动调用.它也会自动向里面传个ActionEvent 对象吗