方法一: 加final 修饰符:
即:在事件处理类中需要访问类变量时,需要加final
方法二:将变量变成类的实例变量,但这种方法扩大了变量的作用范围
public class Helloworld{
//由于引用他的代码是在静态方法内才加static,否则不加static
staticString str="李刚";
publicstaticvoid main(){
........
}
}
方法三:将事件代码写成命名内部类,然后通过构造函数的参数来传入,这种比较繁琐一些。
public class helloworld{
public static void main(String[],agrs){
String str="李刚"
// 通过构造函数参数将Str 值传入
text.addMouseListener(new MyMouseDoubleClick(str) );
}
//匿名内部类MyMouseDoubleClick
private static final class MyMouseDoubleClick extends MouseAdapter{
private String string // 建一变量引用str 的值
public MyMouseDoubleClick(String str){//通过构造函数参数接受str的值
this.string=str;
}
public void mouseDoubleClick(MouseEvent e){
System.out.println(string);
}
}
}