简体   繁体   English

关于Swing计时器的一些问题

[英]Some questions on Swing timer

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 : 在上面的代码中:

  1. TimeClass should be created inside the main() function. 应该在main()函数内部创建TimeClass。 Otherwise it shows the error "non static variable this cannot be referenced from a static context.". 否则,它将显示错误“无法从静态上下文引用的非静态变量”。 Why is this? 为什么是这样?

  2. When I use an access specifier for TimeClass like public or private, I'm getting an illegal start of expression error. 当我对TimeClass使用访问说明符(例如public或private)时,出现非法的表达式开始错误。 Why is this? 为什么是这样?

  1. If you are defining the TimeClass outside of main method, it should be static. 如果要在main方法之外定义TimeClass,则它应该是静态的。 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. 无法从静态块或方法访问非静态变量。

  2. 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: 将您的代码更改为如下所示,然后它可以工作:

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);    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM