大概的内容是把一个按钮添加了事件,点击后在右侧文字,但不明原因要把标签类定义成final类,代码如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class Xck {
public static void main (String[] args) {
JFrame f=new JFrame("my first frame");
f.setSize(250,100);
f.setVisible(true);
/*try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch(Exception e){}
Frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
f.dispose();*/
/*f.addWindowListener(new WindowAdapter()//WindowAdapter是抽象类,实现了所有的WindowListener方法
{
 public void windowClosing(WindowEvent e)
 { System.exit(0);}
});*/
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 Panel p=new Panel();
 p.setLayout(new GridLayout(1,2));
 Button b=new Button("这是按钮");
 final Label l=new Label("这是标签");
b.addActionListener(
new ActionListener()

{
public void actionPerformed(ActionEvent e){l.setText("click!");}
}

                 );
 
 p.add(b);
 p.add(l);
 
f.add(p);


}}

解决方案 »

  1.   

    这是楼主的理解错误,想必楼主是没有好好看《Java编程思想》。根本原因是楼主在内部类里面访问了局部变量,要知道局部变量离开作用域是要被垃圾回收的,也就是说楼主在匿名内部类里面调用l.setText("click!");时,l这个JLabel可以超出作用域已经被垃圾回收了。为了确保这种情况不会发生,只能延长它的生命周期,于是才有了final的存在,是为了保证严谨性。楼主可以把l作为Xck类的属性,也可以不用加final,因为这时候它的生命周期不局限于一个方法,而是与Xck的对象相同。
      

  2.   

    楼上正解。
    public class Xck {
    public static JLabel g=new JLabel(); public static void main(String[] args) {
    JFrame f = new JFrame("my first frame");
    f.setSize(250, 100);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Panel p = new Panel();
    p.setLayout(new GridLayout(1, 2));
    Button b = new Button("这是按钮");
    JLabel l = Xck.g;
    b.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e) {
    Xck.g.setText("这是标签");
    }
    }
    );
    p.add(b);
    p.add(l);
    f.add(p);
    }
    }
      

  3.   

    +1
    在内部类里面访问局部变量必须将其设置为final