gpt4 book ai didi

java - 在 jlabel 背景上添加 jpanel

转载 作者:行者123 更新时间:2023-11-30 03:03:25 25 4
gpt4 key购买 nike

我知道这个问题之前已经被问过,但我似乎无法实现我的项目的任何其他答案。所以我在这里的玩家类中有我的绘制方法。

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);
}
}

现在我似乎无法让我的玩家对象在我的背景上绘画,任何帮助将不胜感激!

最佳答案

有几个错误...

  1. JPanel默认是不透明的,所以需要将其改为透明
  2. JFrame使用 BorderLayout默认情况下,因此只有一个组件会显示在(默认)中心位置,在本例中是您添加的最后一个组件。
  3. 您应该调用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com