繁体   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);

    }
}

在上面的代码中:

  1. 应该在main()函数内部创建TimeClass。 否则,它将显示错误“无法从静态上下文引用的非静态变量”。 为什么是这样?

  2. 当我对TimeClass使用访问说明符(例如public或private)时,出现非法的表达式开始错误。 为什么是这样?

  1. 如果要在main方法之外定义TimeClass,则它应该是静态的。 因为您正在尝试从静态方法(主要)访问它。 无法从静态块或方法访问非静态变量。

  2. 如果要在方法内部定义类(例如您的案例),则不能为其定义任何访问说明符。 因为它只能在您的方法中访问,并且没有人可以在此方法之外看到或使用它。

将您的代码更改为如下所示,然后它可以工作:

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