首页 > 解决方案 > 当我添加计时器时,图像将不再加载

问题描述

我正在尝试创建一个 Asteroids 游戏,但我一开始就在苦苦挣扎:我想在游戏开始前创建一个倒计时。为此,我使用了一个计时器,该计时器在按下“开始”按钮时启动,并且(应该)BufferedImage每秒加载一次,然后将其显示在JFrame.

在我添加计时器之前,整个事情运行良好。但是,图像仍在绘制中,并且仍在使用完整run()的方法。TimerTask但是,图像没有出现在我的JFrame.

public class Main implements ActionListener {

    private static File load = null;
    private static BufferedImage image = null;
    private JFrame frame;
    private JButton start;
    private JLabel game_name;
    private JLabel screen;
    private ImageIcon icon;
    private Asteroids aster = new Asteroids();
    private static Main m = new Main();

    protected static int height = 550;
    protected static int width = 800;
    protected static int cd = 0;

    /*
     * Here the JFrame frame gets created and set up, and the main method 
     * does its job. I believe only the actionPerformed method to be 
     * important, so I removed this part from the post.
     *
     */


    private void addScreen() {
        frame.add(screen);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        // Cleaning the screen
        start.setVisible(false);
        game_name.setVisible(false);

        // Creating the image
        aster.spawn(5);

        // creating the countdown timer
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {            
            public void run() {
                // creating countdown
                aster.initialScreen();

                // Reading the image
                load = new File(aster.filePath + aster.fileName + ".png");
                image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                try {
                image = ImageIO.read(load); 
                } catch (IOException i) {
                    System.out.println("Reading has encountered an error: \n" + i); }

                // Implementing the Image
                screen = new JLabel();
                screen.setSize(width, height);
                icon = new ImageIcon(image);
                screen.setIcon(icon);
                m.addScreen();
                System.out.println("roger");
            }

        }, 0, 1000);

    } // end actionPerfomed()

} // end class

有人能发现错误吗?我真的不明白问题是什么,虽然我是计时器新手,所以如果我做的事情真的很愚蠢,请告诉我。

标签: javaswingtimer

解决方案


您的问题很可能是因为您正在使用java.util.Timer,它会启动自己的后台线程并在您访问 Swing 组件时导致并发问题。

在任何情况下,我都建议使用javax.swing.Timer,它将您的任务安排为在 Swing 事件调度线程上执行的动作侦听器:

new javax.swing.Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
            // Your code here
        }
    }).start();

推荐阅读