在 jlabel 背景上添加 jpanel

Adding a jpanel over a jlabel background

我知道之前有人问过这个问题,但我似乎无法对我的项目实施任何其他答案。所以我在我的播放器 class 中有我的绘画方法。

public void paintComponent(Graphics g)
{
   //makes player(placeholder for real art)
   super.paintComponent(g);
   g.setColor(Color.GREEN);
   g.fillRect(x,y,50,30);
}

那我的主要class就在这里。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class Main here.
* 
* @author Richard Zins 
* @V01
*/
public class Main extends JFrame
{
    public static void main(String[]args)
    {
     Player p1 = new Player();
     Main m = new Main(p1);


     }

     public Main(Player p1)
     {
      JFrame ar = new JFrame();
      JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
      ar.setTitle("Runner Maze");
      ar.setSize(800,600); 
      ar.add(background);
      ar.setVisible(true);
      ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ar.add(p1);
   }
}

现在我似乎无法让我的播放器对象在我的背景上绘制任何帮助!

您可以通过将不透明设置为 false 使 JPanel 透明。例如:

panel.setOpaque(false)

试试这个是否适合你。

使用 JLayeredPane 并在索引 0 处添加您的背景(索引为 Integer 而不是 int)。然后你添加另一个 JPanel 不是不透明的(就像在@Bahramdun Adil 的回答中)并将你的播放器添加到那个。

这样你就可以同时拥有背景和显示你的播放器了。

有几个错误...

  1. JPanel默认是不透明的,需要改成透明
  2. JFrame 默认使用 BorderLayout,因此只有一个组件将显示在(默认)中心位置,在这种情况下,即您添加的最后一个内容。
  3. 你应该最后打电话给 setVisible

相反,为 JLabel 设置布局管理器并将您的播放器 class 添加到其中。不要将 JLabel 添加到框架,而应将框架的标签设置为 contentPane,例如...

p1.setOpaque(false);
JFrame ar = new JFrame();
ar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel background = new JLabel(new ImageIcon("/Users/rizins/Desktop/PacManTestBackGround.jpg"));
ar.setTitle("Runner Maze");
ar.setContentPane(background);
ar.setLayout(new BorderLayout());
ar.add(p1);
ar.pack(); 
ar.setVisible(true);

我应该指出,使用 JLabel 来显示这样的背景图像可能会给您带来问题,因为 JLabel 仅使用文本和图标属性来计算其首选大小,这可能会导致某些子组件的布局超出其可见范围。

有关详细信息和可能的解决方案,请参阅 How to set a background picture in JPanel