计时器不适用于移动球

时间:2017-12-15 21:56:08

标签: java

我正试图让计时器工作来移动球。它只是不起作用。我收到了很多我不理解的错误

有人能告诉我我做错了什么。

这是我得到的错误。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Paneel$TimerHandler.actionPerformed(Paneel.java:30)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

提前致谢。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Paneel extends JPanel 
{
    private int height, width;
    private boolean moveLeft, moveRight, moveUp, moveDown;
    private Timer timer;
    private Ball ball;

    public Paneel() 
    {
        TimerHandler timerHandler = new TimerHandler();
        timer = new Timer(20, timerHandler);
        timer.start();
    }

    public void paintComponent(Graphics pen)
    {
        super.paintComponent(pen);
        ball = new Ball((double)getWidth(), (double)getHeight());
        ball.drawBall(pen);
    }

    class TimerHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e) 
        {
            ball.moveDown();
            repaint();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在每个绘画期间创建一个新的Ball对象

ball = new Ball((double)getWidth(), (double)getHeight());

这意味着在第一次绘画调用之前,球参考是空的。

ball.moveDown(); // ball here could be null

我建议现在在构造函数中定义ball。在我弄清楚如何正确设置其大小之前,我需要查看Ball类的来源。

public Paneel() 
{
    ball = new Ball(0, 0);
    TimerHandler timerHandler = new TimerHandler();
    timer = new Timer(20, timerHandler);
    timer.start();
}