无法旋转JPanel图像

时间:2017-08-15 23:55:13

标签: java swing graphics rotation jpanel

在我正在制作的游戏中,我一直无法旋转我的一个精灵。我已经按照关于在JPanels上旋转图像的教程来了解图像的中心(这是非常好的)。我甚至创建了一个工作得很好的简单项目。

然而,当我尝试在我的游戏中使用相同的技术时,我的精灵不会旋转。我已经确定问题是绘制精灵,因为我已通过paintComponent(Graphics g)语句检查了println()语句,正确更新了旋转值并且正在调用repaint()方法在适当的时候。

以下是该问题的相关代码(不包括不必要的方法等):

最高级别课程:

public abstract class GameObject extends JPanel {

    protected BufferedImage image;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Draw sprite
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(image, 0, 0, null);

        // Clean up
        g.dispose();
        g2.dispose();
    }
}

最低级别的课程:

// Entity is a subclass of GameObject. 
// It does not override paintComponent.
// All it does is add an update method that is called every game tick.

public abstract class MicroObject extends Entity { 

    protected Location location; // variable to store position and rotation

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.translate(this.getWidth() / 2, this.getHeight() / 2);
        g2.rotate(Math.toRadians(location.getRotation()));

        // In the following two lines, image is inherited from GameObject
        g2.translate(-image.getWidth(this) / 2, -image.getHeight(this) / 2);
        g2.drawImage(image, 0, 0, null);

        g2.dispose();
        g.dispose();
    }
}

我知道这不一定是一个独特的问题,但我查看了所有“重复”线程,他们都给我留下了类似的答案,但最后却出现了同样的问题。如果有人花时间查看我的代码,看看我哪里出错,我将不胜感激。

谢谢大家!

1 个答案:

答案 0 :(得分:0)

不要处置那些Graphics对象!它们被Swing重新用于绘制儿童组件和组件。边界。

它不起作用的原因是因为GameObjectMicroObject可以使用它之前处理图形对象。

此外,没有理由两次绘制图像。删除GameObject的{​​{1}}。

中的代码

最后,只需使用类。这些都没有理由是抽象的。

所以:

最高级别课程:

paintComponent()

最低级别的课程:

public class GameObject extends JPanel {

    protected BufferedImage image;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Don't draw sprite. Subclass will do that.

        // Don't clean up. Swing does that for us.
    }
}