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那没有别的组件,它就把它占满了,你点击任何地方都会得到响应的。
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());这样的写法才是正确的!
System.out.println("actionevent 2");
这句不是被你屏蔽了吗?
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那没有别的组件,它就把它占满了,你点击任何地方都会得到响应的。
“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());这样的写法才是正确的!