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);
}
}
In the above code :
-
TimeClass should be created inside the main() function. Otherwise it shows the error “non static variable this cannot be referenced from a static context.”. Why is this?
-
When I use an access specifier for TimeClass like public or private, I’m getting an illegal start of expression error. Why is this?
If you are defining the TimeClass outside of main method, it should be static. because you are trying to access it from a static method (main). accessing non static variables from a static block or method is not possible.
if you are defining a class inside a method (like your case) you cannot define any access specifier for it. because its only accessible within your method and no one can see or use it outside of this method.
Change your code to something like this, then it works: