【发布时间】:2016-05-28 13:21:57
【问题描述】:
我正在用 Java 做一个简单平台游戏的初始部分。我创建了一个名为 entity 的类,它扩展了 JPanel 并成功将其添加到窗口中。
import javax.swing.*;
import java.awt.*;
/**
* Created by bw12954 on 27/05/16.
*/
public abstract class Entity extends JPanel {
private final SpriteSheet sprites;
private Point location;
private Dimension dimensions;
public Entity(int x, int y, int w, int h, SpriteSheet sprites)
{
location = new Point(x, y);
dimensions = new Dimension(w, h);
this.sprites = sprites;
}
public Entity(int x, int y, int w, int h)
{
this(x, y, w, h, null);
}
@Override
public Dimension getPreferredSize()
{
return dimensions;
}
public void setLocation(int x, int y)
{
location.setLocation(x, y);
}
/* Some code removed here for brevity */
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(sprites.get(),
(int)location.getX(),
(int)location.getY(),
null);
}
}
如果我像下面这样直接将它添加到 JFrame 中,那么图形会按照我的预期显示在窗口上(请注意,Player 是 Entity 的一个非常简单的子类)
public class Window {
private JFrame window;
public Window()
{
SwingUtilities.invokeLater(this::run);
}
private void run()
{
try {
window = new JFrame();
window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
window.setLocationByPlatform(true);
window.setUndecorated(true);
Player p = new Player(0,0);
window.add(p);
window.setExtendedState(JFrame.MAXIMIZED_BOTH);
window.setVisible(true);
} catch (IOException e) {
// TODO handle exception
e.printStackTrace();
}
}
}
但是 - 当我创建一个名为 World 的类时,它也扩展了 JPanel,将 that 添加到窗口,然后在其构造函数中使用 add() 方法向它添加一个新的 Player,它没有出现。有趣的是,如果我将setBackground() 添加到 Player/Entity 的构造函数中,我可以在实体应该在的位置看到一个彩色方块。只是 drawImage 似乎不起作用。
如果有人知道这里发生了什么,将不胜感激!
【问题讨论】:
-
提供也有问题的代码。
-
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像。
-
顺便说一句 - 似乎基本问题是布局。在更“这是解决方案”的方法中,在单个
JPanel中绘制每个游戏元素。所以Entity和Player不应该扩展任何JComponent,而只是知道在需要时如何以及在哪里将自己吸引到Graphics实例。 -
谢谢@AndrewThompson,我以后会努力做到的。