import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class ButtenTest{

public static void main(String args[]){
JFrame frame=new JFrame("First Button");
Container contentPane=frame.getContentPane();
JButton b=new JButton("My First Button");
ActionListener listener=new ActionListener();//这里出错
b.addActionListener(listener);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent actionEvent){
System.out.println("hey,stop that");
}
});
contentPane.add(b,BorderLayout.NORTH);
frame.setSize(300,200);
frame.show();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}编译时出错......
请问ActionListener listener=new ActionListener();  这样的语句是否合法?

解决方案 »

  1.   

    非法
    ActionListener是接口,怎么能实例化呢
    b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    System.out.println("hey,stop that");
    }
    });
    这里其实是一个无名内部类实现了ActionListener
      

  2.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class ButtenTest{

    public static void main(String args[]){
    JFrame frame=new JFrame("First Button");
    Container contentPane=frame.getContentPane();
    JButton b=new JButton("My First Button");

                      //有了后面的内部类就好了,这里删去,2楼正解
                      //ActionListener listener=new ActionListener();//这里出错
    //b.addActionListener(listener); b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent actionEvent){
    System.out.println("hey,stop that");
    }
    });
    contentPane.add(b,BorderLayout.NORTH);
    frame.setSize(300,200);
    frame.show();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }