简体   繁体   English

JFrame中的背景图片

[英]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.! 所以我开发了一个Java游戏,我在将图像添加到My JFrame时得到了什么,它是一个球和球拍游戏,我正在使用eclipse。我个人认为它的目录问题,所以作为参考我已经把png src文件夹中的文件。! Here is the Code for my Game2 Class: 这是我的Game2类的代码:

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: 这是我的Raquet课程:

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 您应该使用这样的URL嵌入资源

     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. 您的图像应与您的类文件位于同一位置,使用此“bg.png”相对路径。 Note: .class file, not .java file. 注意: .class文件,而不是.java文件。

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

The above is Eclipse file structure. 以上是Eclipse文件结构。 In Netbeans you want to look in build/classes/challenger/ 在Netbeans中,您希望查看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 请参见如何使用JLayeredPane

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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