package xyz;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class XYZ {
public static void main(String[] args) throws InterruptedException {
class TimeClass implements ActionListener {
private int counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
counter++;
System.out.println(counter);
}
}
Timer timer;
TimeClass tc = new TimeClass();
timer = new Timer (100, tc);
timer.start();
Thread.sleep(20000);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中:
应该在main()函数内创建TimeClass.否则,它会显示错误"非静态变量,这不能从静态上下文中引用".为什么是这样?
当我使用TimeClass的访问说明符如public或private时,我得到了一个非法的表达式错误启动.为什么是这样?
如果要在main方法之外定义TimeClass,它应该是静态的.因为您试图从静态方法(主)访问它.从静态块或方法访问非静态变量是不可能的.
如果要在方法内部定义类(如您的情况),则无法为其定义任何访问说明符.因为它只能在您的方法中访问,并且没有人可以在此方法之外查看或使用它.
将您的代码更改为这样的代码,然后它可以工作:
public class Test {
private static class TimeClass implements ActionListener {
private int counter = 0;
@Override
public void actionPerformed(ActionEvent e) {
counter++;
System.out.println(counter);
}
}
public static void main(String[] args) throws InterruptedException {
TimeClass tc = new TimeClass();
Timer timer = new Timer (100, tc);
timer.start();
Thread.sleep(20000);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
90 次 |
最近记录: |