有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    在每次绘制期间,您将创建一个新的Ball对象

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

    这意味着在第一次绘制调用之前,ball引用为null

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