N次执行后停止摆动计时器

ocr*_*ram 0 java swing timer

我写了这个应该运行10次然后停止的Swing计时器.但是,编译器说Timer没有初始化.我不想初始化它,我不需要(这里是一个没有初始化并且工作正常的例子).怎么了?

public Enhanced() {
    Timer picTimer ;
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 422);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    JLabel lblTimer = new JLabel();
    lblTimer.setBounds(361, 67, 61, 16);
    contentPane.add(lblTimer);

    ActionListener a = new ActionListener() {
        int time=0;
        @Override
        public void actionPerformed(ActionEvent e) {


            System.out.println("hello");

            if (++time > 10) {
                picTimer.stop();
                System.exit(0);
            }
        }
    };
    picTimer = new Timer(1000,a);

}
Run Code Online (Sandbox Code Playgroud)

Rea*_*tic 5

有一种方法可以避免引用外部计时器变量.

计时器实际上是您每次收到的事件的来源ActionListener.因此,您可以通过调用来访问它e.getSource().

这样,您甚至不需要提前声明计时器:

ActionListener a = new ActionListener() {
    int time=0;
    @Override
    public void actionPerformed(ActionEvent e) {


        System.out.println("hello");

        if (++time > 10) {
            Timer timer = (Timer)e.getSource();
            timer.stop();
            System.exit(0);
        }
    }
};

new Timer(1000,a).start();
Run Code Online (Sandbox Code Playgroud)

请注意,这样调用System.exit()无论如何都会停止计时器.真的不建议这样打电话System.exit().