将图像作为 JPanel 的背景

Having images as background of JPanel(将图像作为 JPanel 的背景)

本文介绍了将图像作为 JPanel 的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,目前正在创建一个带有图形的游戏.我有这个类从 JFrame 扩展而来.在这个类中,我有许多需要图像作为背景的 JPanel.据我所知,为了能够在 JPanel 中绘制图像,我需要有一个从 JPanel 扩展而来的单独类,并且该类的 paintComponent 方法将完成这项工作.但是我不想为每个 JPanel 单独的类,我有太多的类;而且我只关心背景.我怎样才能做到这一点?是匿名内部类吗?怎么样?

I am new in Java and I am currently creating a game with graphics. I have this class that extends from JFrame. In this class, I have many JPanels that needs an image as background. As I know, to be able to paint images in the JPanel, I need to have a separate class that extends from JPanel and that class's paintComponent method will do the work. But I don't want to make separate classes for each JPanel, I have too many of them; and with the fact that I am only concerned with the background. How can I do this? is it with an anonymous inner class? How?

为了更好地理解,我提供了一些代码:

For better understanding I provided some code:

public GUI extends JFrame {
  private JPanel x;
  ...  

  public GUI() {
   x = new JPanel();
   // put an image background to x
  }

推荐答案

为什么不创建一个接受 Image 的单个类??

Why not make a single class that takes a Image??

public class ImagePane extends JPanel {

    private Image image;

    public ImagePane(Image image) {
        this.image = image;
    }

    @Override
    public Dimension getPreferredSize() {
        return image == null ? new Dimension(0, 0) : new Dimension(image.getWidth(this), image.getHeight(this));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.drawImage(image, 0, 0, this);
        g2d.dispose();
    }
}

你甚至会提供关于应该在哪里绘制的提示.

You would even provide hints about where it should be painted.

这样,您可以在需要时简单地创建一个实例

This way, you could simply create an instance when ever you needed it

更新

另一个问题是,为什么?

The other question is, why?

您可以只使用 JLabel 来为您绘制图标,而无需任何额外工作...

You could just use a JLabel which will paint the icon for you without any additional work...

有关详细信息,请参阅 如何使用标签..

See How to use labels for more details...

这实际上是一个坏主意,因为 JLabel 在计算其首选尺寸时不使用它的子组件,它仅在确定其首选尺寸时使用图像的大小和文本属性,这个可能导致组件尺寸不正确

This is actually a bad idea, as JLabel does NOT use it's child components when calculating it's preferred size, it only uses the size of the image and the text properties when determining it's preferred size, this can result in the component been sized incorrectly

这篇关于将图像作为 JPanel 的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将图像作为 JPanel 的背景

上一篇: JFrame 背景图片
下一篇: 游戏的无限背景