下面程序出问题在那里啊?谢谢import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDemo5 {
JButton b1,b2;
public EventDemo5()
{
JFrame f=new JFrame("Eventdemo5");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));
JButton b1=new JButton("soud");
JButton b2=new JButton("new frame");
b1.addActionListener(this);
b2.addActionListener(this);
f.add(b1);
f.add(b2);
f.pack();
f.show();
f.addWindowListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()==b1)
Toolkit.getDefaultToolkit().beep();
else
{
JFrame f2=new JFrame("我是新的窗口哦】");
f2.show();
}
}
public void windowClosing(WindowEvent e){
System.exit(0);
};//监听窗口的方法
public static void main(String args[]){
new EventDemo5();
}
}
import java.awt.event.*;
import javax.swing.*;
public class EventDemo5 {
JButton b1,b2;
public EventDemo5()
{
JFrame f=new JFrame("Eventdemo5");
Container contentPane=f.getContentPane();
contentPane.setLayout(new GridLayout(1,2));
JButton b1=new JButton("soud");
JButton b2=new JButton("new frame");
b1.addActionListener(this);
b2.addActionListener(this);
f.add(b1);
f.add(b2);
f.pack();
f.show();
f.addWindowListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()==b1)
Toolkit.getDefaultToolkit().beep();
else
{
JFrame f2=new JFrame("我是新的窗口哦】");
f2.show();
}
}
public void windowClosing(WindowEvent e){
System.exit(0);
};//监听窗口的方法
public static void main(String args[]){
new EventDemo5();
}
}
b2.addActionListener(this); f.addWindowListener(this); this 是EventDemo5,根本就不是任何监听器,怎么能作为监听器添加到组件和Frame呢。
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){});
其中这个this 代表new ActionListener()
其调用 actionPerformed(ActionEvent e)是合理的
但是在类中实现了 public void actionPerformed(ActionEvent e) 方法不代表这个类就是一个ActionListener吧!
public void addActionListener(ActionListener l)
可以看出,参数是一个ActionListener接口的实现类对象。又从Window类的方法
public void addWindowListener(WindowListener l)
可以看出,参数是一个WindowListener接口的实现类对象。你声明的类EventDemo5并不是这两个接口的实现,因此不能作为上述两个方法的参数。
可以把你的类声明改成:public class EventDemo5 extends WindowAdapter implements ActionListenerp.s. 因为并未实现WindowLinstener接口的所有方法,因此采用继承其子类:接收窗口事件的抽象适配器类WindowAdapter。
b2.addActionListener(this); f.addWindowListener(this);
还要继承
我认同marcien 的看法