日期:2014-05-20  浏览次数:20699 次

刚学监听 抄了书的一段代码不能用运行 求解
Java code

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
class ButtonActionFrame extends JFrame
{
    ButtonActionFrame()
    {
        super("按钮响应");
        setSize(250,200);
        setLocation(400,300);
        JButton jb=new JButton("OK");
        JPanel jp=new JPanel();
        jp.add(jb);
        add(jp);
        ButtonListener bla=new ButtonListener();    //创建监听对象
        jp.addActionListener(bla);//注册监听对象
    }
}
class ButtonListener implements ActionListener        //定义监听类
{
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("你单击了按钮!");
    }
}


public class Example7_6 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame f=new ButtonActionFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

}





jp.addActionListener(bla);//注册监听对象 这里提示有问题

------解决方案--------------------
jp.addActionListener(bla);//注册监听对象 这里提示有问题
你写错了,你的按钮是jb;
------解决方案--------------------
jp.addActionListener(bla)
改为
jp.addActionListener(new ButtonListener())
------解决方案--------------------
1L 正解! 应该是LZ 没有理解,因为button 是observer ,
你点击了button ,触发了事件,这时去通知 listener ,
所以应该是 向 buuton (也就是你的 jb)添加listener(也就是你的bla) 

把这个 jp.addActionListener(bla);//注册监听对象 这里提示有问题

改成 jb.addActionListener(bla);应该没有问题了