我觉得你对事件的理解不太对,在这里你的程序继承了Jpanel,但Jpanel不会产生action事件。还有好像addActionListener()是不要自己去实现的吧?
[我也不太懂,仅供参考]

解决方案 »

  1.   

    你什么意思?
    System.out.println("actionevent 2");
    这句不是被你屏蔽了吗?
      

  2.   

    代码本身没有多大的问题。问题出在布局管理器的使用,如使用默认的BorderLayout,效果非常明显。但即便使用FlowLayout也有响应,只是响应的区间非常狭小。原因大概是FlowLayout这种布局管理器适合于可视部件,如button或checkbox,亦或该例程对FlowLayout这种布局管理器的控制不当所致。
      

  3.   

    think in java有这样一句话:
    All components will be compacted to their smallest size in a FlowLayout, so you might get a little bit of surprising behavior. For example, because a JLabel will be the size of its string, attempting to right-justify its text yields an unchanged display when using FlowLayout。
    而panel是作为容器组件使用的,当他本身不容纳其他组件时,大小为零,所以无法响应你的动作。而BorderLayout布局方式不同,他会占据尽可能大的空间,你的frame那没有别的组件,它就把它占满了,你点击任何地方都会得到响应的。
      

  4.   

    JPanel 的事件应该是ComponentListener而不是ActionListener,所以actionPerformed事件从来不会被触发,如果你把public class test extends JPanel 换成public class test extends JButton,则在按钮上点击时,会输出
    “actionevent 1”,但
    System.out.println("registing a actionlistener");
    al=a;
    System.out.println("register listener over"); System.out.print(al);
    这段代码是没有意义的,也许只会在程序运行的开始会执行,
    t.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent a){
    System.out.println("actionevent 1");
    }
    实际上是用到了匿名类,addMouseListener(new MH());这样的写法才是正确的!