English 中文(简体)
我在我的大游戏中展现了我的背景形象。
原标题:My background image isn t displaying in my pong game I made

My background image is failing to load in my pong game I created with Java. This is my GamePanel.java file where I believe the error is coming from.

import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Stroke;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.net.URL;

public class GamePanel extends JPanel implements ActionListener, KeyListener {
    static final int GAME_WIDTH = 800;
    static final int GAME_HEIGHT = 600;
    static final int BALL_DIAMETER = 20;
    static final int PADDLE_WIDTH = 10;
    static final int PADDLE_HEIGHT = 100;
    Paddle player1;
    Paddle player2;
    Ball ball;
    Timer timer;
    int player1Score = 0;
    int player2Score = 0;
    boolean playState = true;
    private Image backgroundImage;
    private SoundEffect scoreSound;  // Declaration of the SoundEffect object

    public GamePanel() {
        player1 = new Paddle(0, (GAME_HEIGHT / 2) - (PADDLE_HEIGHT / 2), PADDLE_WIDTH, PADDLE_HEIGHT, 1);
        player2 = new Paddle(GAME_WIDTH - PADDLE_WIDTH, (GAME_HEIGHT / 2) - (PADDLE_HEIGHT / 2), PADDLE_WIDTH, PADDLE_HEIGHT, 2);
        ball = new Ball((GAME_WIDTH / 2) - (BALL_DIAMETER / 2), (GAME_HEIGHT / 2) - (BALL_DIAMETER / 2), BALL_DIAMETER, BALL_DIAMETER);
        loadImage();
        scoreSound = new SoundEffect("/sounds/score.wav");  // Initialize the sound effect

        this.setFocusable(true);
        this.addKeyListener(this);
        this.setPreferredSize(new java.awt.Dimension(GAME_WIDTH, GAME_HEIGHT));
        timer = new Timer(10, this);
        timer.start();
    }

    private void loadImage() {
        // Example path that assumes the  images  folder is directly in the project root directory
        String path = "/images/backgroundImage.png"; // Adjust this path as needed
        URL url = getClass().getClassLoader().getResource(path);
        if (url == null) {
            System.err.println("Failed to load background image: " + path);
            return;
        }
        ImageIcon ii = new ImageIcon(url);
        backgroundImage = ii.getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (backgroundImage != null) {
            g.drawImage(backgroundImage, 800, 600, this.getWidth(), this.getHeight(), this); // Draw the background full-size
        }
        drawScoreboard(g);
        drawCenterLine(g);
        player1.draw(g);
        player2.draw(g);
        ball.draw(g);
    }
    public void scoreUpdate(int player) {
        if (player == 1) {
            player1Score++;  // Correctly increment player1 s score
        } else if (player == 2) {
            player2Score++;  // Correctly increment player2 s score
        }
        scoreSound.play(); // Play sound on scoring
    }
    

    public void actionPerformed(ActionEvent e) {
        if (playState) {
            player1.move();
            player2.move();
            ball.move();
        }
        checkCollision();
        repaint();
    }

    public void checkCollision() {
        // Ball bounces off top & bottom window edges
        if (ball.y <= 0 || ball.y >= GAME_HEIGHT - ball.height) {
            ball.setYDirection(-ball.yVelocity);
        }

        // Ball bounces off paddles
        if (ball.intersects(player1) || ball.intersects(player2)) {
            ball.setXDirection(-ball.xVelocity);
        }

        // Ball goes out of bounds
        if (ball.x <= 0) {
            scoreUpdate(2);
            playState = false;
            newPaddles();
            newBall();
            ball.stop();
        } else if (ball.x >= GAME_WIDTH - ball.width) {
            scoreUpdate(1);
            playState = false;
            newPaddles();
            newBall();
            ball.stop();
        }
    }

    public void newPaddles() {
        player1.y = (GAME_HEIGHT / 2) - (PADDLE_HEIGHT / 2);
        player2.y = (GAME_HEIGHT / 2) - (PADDLE_HEIGHT / 2);
    }

    public void newBall() {
        ball.x = (GAME_WIDTH / 2) - (BALL_DIAMETER / 2);
        ball.y = (GAME_HEIGHT / 2) - (BALL_DIAMETER / 2);
    }




    private void drawScoreboard(Graphics g) {
        g.setColor(Color.WHITE);
        g.setFont(new Font("Consolas", Font.BOLD, 60));
        g.drawString(String.valueOf(player1Score), (GAME_WIDTH / 4), 50);
        g.drawString(String.valueOf(player2Score), (GAME_WIDTH / 4) * 3, 50);
    }

    private void drawCenterLine(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{10}, 0);
        g2d.setStroke(dashed);
        g2d.setColor(Color.WHITE);
        g2d.drawLine(GAME_WIDTH / 2, 0, GAME_WIDTH / 2, GAME_HEIGHT);
    }

    public void keyPressed(KeyEvent e) {
        player1.keyPressed(e);
        player2.keyPressed(e);
        if (e.getKeyCode() == KeyEvent.VK_SPACE && !playState) {
            playState = true;  // Start moving the ball again
            int direction = (player1Score + player2Score) % 2 == 0 ? 1 : -1;
            ball.start(direction);  // Serve the ball towards the last scorer
        }
    }

    public void keyReleased(KeyEvent e) {
        player1.keyReleased(e);
        player2.keyReleased(e);
    }

    public void keyTyped(KeyEvent e) {}
}

My file format:
My file format

I tried renaming files and changing the naming conventions to make sure everything was the same. I have tried differnt png files to see if it was some issue with the png file i was using. I have even consulted AI with this problem and haven t come up with any better results.

问题回答

这似乎是错误的。 这里的x、 y坐标将远远远离中心或框架的边缘:

g.drawImage(backgroundImage, 800, 600, this.getWidth(),
    this.getHeight(), this);

以<条码>0、0取代<条码>800、600 只是看这是否解决问题。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签