我知道这个问题之前已经被问过,但我似乎无法实现我的项目的任何其他答案。所以我在这里的玩家类中有我的绘制方法。
public void paintComponent(Graphics g)
{
//makes player(placeholder for real art)
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(x,y,50,30);
}
然后我的主课就在这里。
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);
}
}
现在我似乎无法让我的玩家对象在我的背景上绘画,任何帮助将不胜感激!
最佳答案
有几个错误...
-
JPanel
默认是不透明的,所以需要将其改为透明 -
JFrame
使用BorderLayout
默认情况下,因此只有一个组件会显示在(默认)中心位置,在本例中是您添加的最后一个组件。 - 您应该调用
setVisible
最后
相反,为 JLabel
设置布局管理器并将您的玩家类别添加到其中。而不是添加 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了解更多详细信息和可能的解决方案
关于java - 在 jlabel 背景上添加 jpanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389259/