在Java Breakout Game中为JPanel设置背景图片

时间:2013-03-18 14:53:53

标签: java swing jpanel paint imageicon

好的,这似乎是一个非常简单的任务,但我似乎无法得到它。我想要的只是将图像(jpg)作为我的突破游戏的背景。这是我的代码:

主类:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Breakout extends JFrame {

    public Breakout()
    {             
        add(new BreakBoard());
        setTitle("Breakout");
        setSize(BreakCommons.WIDTH, BreakCommons.HEIGTH);
        setLocationRelativeTo(null);
        setIgnoreRepaint(true);
        setResizable(false);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Breakout();
    }
}

董事会成员:

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class BreakBoard extends JPanel implements BreakCommons {

    ImageIcon icon = new ImageIcon("../pacpix/love.jpg"); 
    Timer timer;
    String message = "Game Over";
    BreakBall ball;
    BreakPaddle paddle;
    BreakBrick bricks[];
    boolean ingame = true;
    int timerId;


    public BreakBoard() {
        setOpaque(false);
        addKeyListener(new TAdapter());
        setFocusable(true);
        //setBackground(Color.white);
        bricks = new BreakBrick[30];
        setDoubleBuffered(true);
        timer = new Timer();
        timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.drawImage(icon.getImage(), 10, 10, this);

        if (ingame) {
            g.drawImage(ball.getImage(), ball.getX(), ball.getY(),
                        ball.getWidth(), ball.getHeight(), this);
            g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
                        paddle.getWidth(), paddle.getHeight(), this);

            for (int i = 0; i < 30; i++) {
                if (!bricks[i].isDestroyed())
                    g.drawImage(bricks[i].getImage(), bricks[i].getX(),
                                bricks[i].getY(), bricks[i].getWidth(),
                                bricks[i].getHeight(), this);
            }
        } else {

            Font font = new Font("Verdana", Font.BOLD, 18);
            FontMetrics metr = this.getFontMetrics(font);

            g.setColor(Color.BLACK);
            g.setFont(font);
            g.drawString(message,
                         (BreakCommons.WIDTH - metr.stringWidth(message)) / 2,
                         BreakCommons.WIDTH / 2);
        }


        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

因此图像存储在变量icon中,并且位于我的源文件中(以及我的类),所以我知道路径是正确的。我尝试将框架和面板设置为setOpaque(false),但这只是将背景更改为默认灰色。我可以轻松地按setBackground(Color.white);设置背景颜色,但如何设置图像?

我尝试将图像放入JLabel,然后将其添加到JPanel,但这没有产生任何结果。我将不胜感激任何帮助,并提前感谢!我可以根据需要提供更多信息。

4 个答案:

答案 0 :(得分:2)

简单方法首先为jpane创建一个单独的类

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class JPanelDemo extends JPanel {
    /**
     * 
     */
     private static final long serialVersionUID = 1L;
     private static final Color BACKGROUND      = Color.black;
     private static final Color BACKGROUND_2    = Color.WHITE;
     String path="/img/background.jpg";

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D graphics = (Graphics2D) g.create();        
        int midY = 100;
        Paint topPaint = new GradientPaint(0, 0, BACKGROUND,0, midY, BACKGROUND_2);
        graphics.setPaint(topPaint);
        graphics.fillRect(0, 0, getWidth(), midY);        
        Paint bottomPaint = new GradientPaint(0, midY + 1, BACKGROUND_2,0, getHeight(), BACKGROUND);
        graphics.setPaint(bottomPaint);
        graphics.fillRect(0, midY, getWidth(), getHeight());
        Image img = new ImageIcon(getClass().getResource(path)).getImage();
        int imgX = img.getWidth(null);
        int imgY = img.getHeight(null);
        graphics.drawImage(img, (getWidth() - imgX) / 2, (getHeight() - imgY) / 2, imgX, imgY, null);
      //  graphics.dispose();
    }
}

如何使用

JPanelDemo contentPane = new JPanelDemo();

答案 1 :(得分:1)

这是一张带有背景图片的JPanel。在代码中使用IPanel代替JPanel。根据需要调整以满足您的需求。

public class IPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image             imageOrg         = null;
private Image             image            = null;
{
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(final ComponentEvent e) {
            final int w = IPanel.this.getWidth();
            final int h = IPanel.this.getHeight();
            image = w > 0 && h > 0 ? imageOrg.getScaledInstance(w, h, Image.SCALE_SMOOTH) : imageOrg;
            IPanel.this.repaint();
        }
    });
}

public IPanel(final Image i) {
    imageOrg = i;
    image = i;
}

@Override
public void paintComponent(final Graphics g) {
    super.paintComponent(g);
    if (image != null)
        g.drawImage(image, 0, 0, null);
}
}

示例:

    final JPanel j = new IPanel(image);
    j.setLayout(new FlowLayout());
    j.add(new JButton("YoYo"));
    j.add(new JButton("MaMa"));
    j.add(new JLabel(icon));

产地:

enter image description here

答案 2 :(得分:1)

我终于开始工作了!

public class BreakBoard extends JPanel implements BreakCommons {
    Image love;

    public BreakBoard() {
        ImageIcon icon = new ImageIcon(this.getClass().getResource("../pacpix/love.jpg"));
        love = icon.getImage();
    }

    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(love, 10, 10, null); 
    }
}

对于将来的搜索或好奇的搜索,我使用了http://zetcode.com/tutorials/javagamestutorial/basics/。适合初学者的好网站! (或者那些需要深入了解的人)

答案 3 :(得分:1)

JPanel panel = new JPanel()    
{       
          @Override
          public void paintComponent(Graphics g) 
          {     
                g.drawImage(ImageObject, 0, 0, null);
          }
};