如何向 JPanel 添加背景图像?

How do I add a background image to a JPanel?

我有一个 JFrame,里面有 JPanel。我的游戏背景是全黑的,因为实体在它上面。我只想以 "simplest" 的方式将背景更改为计算机中的图像,而无需进行太多更改。

public Game() {
    // Frame
    JFrame container = new JFrame("Space Invaders");

    // Resolution
    JPanel panel = (JPanel) container.getContentPane();
    panel.setPreferredSize(new Dimension(800,600));
    panel.setLayout(null);

    // Canvas Size
    panel.setBounds(0,0,800,600);
    panel.add(this);

    // Window Visible
    container.pack();
    container.setResizable(false);
    container.setVisible(true);

    container.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

你可以...

使用JLabel作为背景组件...

JFrame container = new JFrame("Space Invaders");
JLabel label = new JLabel(new ImageIcon(ImageIO.read(...)));
label.setLayout(new BorderLayout());
container.setContentPane(label);

// Resolution
// There are simply so many different ways to achieve this
// that are better it's not funny
//JPanel panel = (JPanel) container.getContentPane();
//panel.setPreferredSize(new Dimension(800, 600));
//panel.setLayout(null);

// Canvas Size
//setBounds(0, 0, 800, 600);
//panel.add(this);

// Window Visible
container.pack();
container.setResizable(false);
container.setVisible(true);

container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Pointless
//container.addWindowListener(new WindowAdapter() {
//    public void windowClosing(WindowEvent e) {
//          System.exit(0);
//      }
//});

问题是:

  1. 标签只会使用icontext属性来计算标签
  2. preferredSize
  3. 如果您使用的是 java.awt.Canvas,那么它将在该组件上绘制,因为 java.awt.Canvas 不能透明。

有关详细信息,请参阅 Reading/Loading an Image and How to Use Labels

你可以...

在渲染内容重置之前使用Graphics#drawImage绘制背景图像。

这通常是更好的解决方案,因为您可以完全控制图像的大小和位置,并且如果您使用 java.awt.CanvasBufferStrategy

有关详细信息,请参阅 2D Graphics and Working with Images