2013-02-11 91 views
1

我有下面的代码,我在第19行得到一个错误“无法为最终变量计数赋值”,但我必须将该变量指定为final以便在“LISTENER”中使用它。错误在哪里?Actionevent最终变量?

import java.awt.event.*; 
import javax.swing.*; 


public class ButtonTester 
{ 
    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     JButton button = new JButton(); 
     frame.add(button); 

     final int count = 0; 

     class ClickListener implements ActionListener 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       count++; 
       System.out.println("I was clicked " + count + " times"); 
      } 
     } 

     ActionListener listener = new ClickListener(); 
     button.addActionListener(listener); 

     frame.setSize(100,60); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 

回答

2

您在ClickListener类中使用了count,但是它在类之外声明。你只在ClickListener内部使用它,所以请在那里移动声明。也可以使这个类是静态的:

static class ClickListener implements ActionListener 
    { 
     private int count = 0; 
     public void actionPerformed(ActionEvent event) 
     { 
      count++; 
      System.out.println("I was clicked " + count + " times"); 
     } 
    } 
+0

Thx perfect!它的工作原理,但我不能声明类静态 – Alpan67 2013-02-11 15:16:21

+0

你将不得不把它从主要的方法,并在'ButtonTester'类中声明它。或者,如果您有其他代码未显示,则可能无法将其设置为静态。尽可能使嵌套类静态是一个好习惯。如果你不能那么好。 – wolfcastle 2013-02-11 15:52:08

1

移动ClickListener中的变量,这是你真正想要的。 如果您将该变量移动到类外部,它必须是最终的,因为它将被视为常量。

4

A final变量一旦被赋值就不能被修改。解决方法是使变量成为ClickListener类的成员:

import java.awt.event.*; 
import javax.swing.*; 


public class ButtonTester 
{ 
    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     JButton button = new JButton(); 
     frame.add(button); 

     class ClickListener implements ActionListener 
     { 
      int count = 0; 
      public void actionPerformed(ActionEvent event) 
      { 
       count++; 
       System.out.println("I was clicked " + count + " times"); 
      } 
     } 

     ActionListener listener = new ClickListener(); 
     button.addActionListener(listener); 

     frame.setSize(100,60); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
}