Hey, ich bin gerade dabei ein Spielfeld mit nem bewegten Ball zu programmieren.
Hier ist der Quellcode der Klasse PingPong:
Hier die Klasse Frame:
Hier die Klasse Ball:
Und die Fehlermeldung:
Ich bin wirklich ratlos und wäre über jede Hilfe dankbar.
Mfg
Hier ist der Quellcode der Klasse PingPong:
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PingPong extends JPanel implements ActionListener{
private Ball ball = new Ball(485, 240, this);
private Image spielfeld;
private Timer timer;
public PingPong () {
setBackground(Color.black);
ImageIcon iiSF = new ImageIcon(this.getClass().getResource("Spielfeld.png"));
spielfeld = iiSF.getImage();
timer = new Timer(15, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(spielfeld, 0, 0, this);
ball.paint(g);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
ball.moveBall();
repaint();
}
}
Hier die Klasse Frame:
Code:
import javax.swing.JFrame; //JFrame komponenten
public class Frame extends JFrame{
public static int x = 1000;
public static int y = 500;
public Frame() {
add(new PingPong()); // Verknüpfung zur Klasse game
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(x, y); //ingame Variablen breite:320 höhe:340, da 20 * 16 = 320 + RÄNDER
setLocationRelativeTo(null);
setTitle("Pong");
setResizable(false); // Größe unveränderbar
setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}
Hier die Klasse Ball:
Code:
import java.awt.*;
import javax.swing.*;
public class Ball {
private int x, y;
private int velocityX, velocityY;
Image ball;
private Component component;
//-----------------------------------------------------------------
public Ball(int x, int y, Component component) {
this.x = x;
this.y = y;
this.component = component;
this.velocityX = 5;
this.velocityY = 5;
ImageIcon iiBall = new ImageIcon(this.getClass().getResource("Ball.png"));
ball = iiBall.getImage();
}
//-----------------------------------------------------------------
public int getX() {
return x;
}
public int getY() {
return y;
}
//-----------------------------------------------------------------
public void moveBall() {
if (x + 50 > 1020) {
velocityX = -5;
} else if (x < 10) {
velocityX = 5;
}
if (y + 40 > 480) {
velocityY = -5;
} else if (y < 10) {
velocityY = 5;
}
x += velocityX;
y += velocityY;
}
//-----------------------------------------------------------------
public void paint(Graphics g) {
g.drawImage(ball, x, y, component);
}
}
Und die Fehlermeldung:
Code:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Ball.<init>(Ball.java:24)
at PingPong.<init>(PingPong.java:7)
at Frame.<init>(Frame.java:10)
at Frame.main(Frame.java:22)
Ich bin wirklich ratlos und wäre über jede Hilfe dankbar.
Mfg