简体   繁体   中英

Background Image in JFrame

So I developed a game in Java and I'm getting othing while adding image to My JFrame,Its a ball and racket game,I'm using eclipse.I personally think its the directory problem,so for reference I've put the png files in src folder.! Here is the Code for my Game2 Class:

package Challenger;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game2 extends JPanel {

Ball ball = new Ball(this);
Ball ball2 = new Ball(this);
Racquet racquet = new Racquet(this);
float speed = (float) 1.0;
int score;
private JButton playMore;
private JButton exitPlease;
static JFrame frame = new JFrame("Challenger");
private Icon defaultImg;
private JLabel bck;

private int getScore() {
    return score;
}

public Game2() {
    addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            racquet.keyReleased(e);
        }

        @Override
        public void keyPressed(KeyEvent e) {
            racquet.keyPressed(e);
        }
    });
    setFocusable(true);
    bck=new JLabel(new ImageIcon("bg.png"));
    bck.setBounds(0, 0, 300, 400);
    frame.add(bck);
}

private void move() {
    ball.move();

    if(score >= 10)
    {
        float tempSpeed = ball2.getSpeed();
        ball2.move2(tempSpeed);

    }
    racquet.move();
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    Graphics2D g3d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    ball.paint(g2d);
    racquet.paint(g2d);

    if( score >= 10)
    {
        ball2.paint(g3d);
    }

    g2d.setColor(Color.RED);
    g2d.setFont(new Font("Verdana", Font.BOLD, 20));
    g2d.drawString("Score: "+ String.valueOf(getScore()), 10, 30);
}

public void gameOver() {
    JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
    JOptionPane.showMessageDialog(this, "Your score is: " + getScore(),
            "Game Over", JOptionPane.YES_NO_OPTION);

    JOptionPane.showMessageDialog(this, "Created By:\n1) DDP-FA12-BCS-009\n2) DDP-FA12-BCS-230\n3) DDP-FA12-BCS-165\n", "Game Over", JOptionPane.YES_NO_OPTION);
    System.exit(ABORT);
}

public static void main(String[] args) throws InterruptedException {
    Game2 game = new Game2();
    frame.add(game);
    frame.setSize(300, 400);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setAlwaysOnTop(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {
        game.move();
        game.repaint();
        Thread.sleep(10);
    }
}
}

This is my Ball Class:

package Challenger;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Ball {
private static final int DIAMETER = 30;
float x = 0;
float y = 0;
float xa = 1;
float ya = 1;
private Game2 game;

public Ball(Game2 game) {
    this.game= game;
}

void move() {
    boolean changeDirection = true;
    if (x + xa < 0.0)
        xa = game.speed;
    else if (x + xa > game.getWidth() - DIAMETER)
        xa = -game.speed;
    else if (y + ya < 0.0)
        ya = game.speed;
    else if (y + ya > game.getHeight() - DIAMETER)
        game.gameOver();
    else if (collision()){
        ya = -game.speed;
        y = game.racquet.getTopY() - DIAMETER;
        game.score++;
        game.speed = (float) (game.speed + 0.10);
    } else 
        changeDirection = false;

    x = x + xa;
    y = y + ya;
}

void move2(float speed) {
    boolean changeDirection = true;
    if (x + xa < 0.0)
        xa = speed;
    else if (x + xa > game.getWidth() - DIAMETER)
        xa = -speed;
    else if (y + ya < 0.0)
        ya = speed;
    else if (y + ya > game.getHeight() - DIAMETER)
        game.gameOver();
    else if (collision()){
        ya = -speed;
        y = game.racquet.getTopY() - DIAMETER;
        game.score++;
        speed = (float) (speed + 0.25);
    } else 
        changeDirection = false;


    x = x + xa;
    y = y + ya;
}

public float getSpeed(){
    return game.speed;

}

public void paint(Graphics2D g) {
    g.setColor(Color.BLUE);
    g.fillOval((int) x, (int) y, 30, 30);
}

private boolean collision() {
    return game.racquet.getBounds().intersects(getBounds());
}

public Rectangle getBounds() {
    return new Rectangle((int) x, (int) y, DIAMETER, DIAMETER);
}
}

and This is my Raquet Class:

package Challenger;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

public class Racquet {
int x = 0;
int xa = 0;
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
private Game2 game;

public Racquet(Game2 game) {
    this.game= game;
}

public void move() {
    if (x + xa > 0 && x + xa < game.getWidth()-60)
        x = x + xa;
}

public void paint(Graphics2D g) {
    g.setColor(Color.BLACK);
    g.fillRect(x, 330, 60, 10);
}

public void keyReleased(KeyEvent e) {
    xa = 0;
}

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_LEFT)
        xa = (int) (-game.speed - 1);
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
        xa = (int) (game.speed + 1);
}

public Rectangle getBounds() {
    return new Rectangle(x, Y, WIDTH, HEIGHT);
}

public int getTopY() {
    return Y;
}
}
  • You should embed resources using a URL like this

     java.net.URL url = getClass().getResource("bg.png"); if (url != null) { bck = new JLabel(new ImageIcon(url); } else { System.err.println("Could not find Image"); } 

Your image should be in the same location as your class file, using this "bg.png" relative path. Note: .class file, not .java file.

   ProjectRoot
            bin
               challenger
                        Racquet.class
                        Ball.class
                        Game2.class
                        bg.png

The above is Eclipse file structure. In Netbeans you want to look in build/classes/challenger/

  • If you're planning to have a painted panel for your game on top of your background, you may want to use a layered pane. You are adding the background label, then add the game panel to the frame. This will not give you aa layered effect

See How to Use a JLayeredPane

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM