Java帮助! paintComponent的困境

时间:2014-04-20 03:08:46

标签: java swing rotation paintcomponent

我是Java新手,每天都在学习新东西。 我正在尝试学习如何使用两个不同的.png文件并使用paint组件单独旋转它们。 我可以使两个图像都绘制并具有单独的移动,但旋转功能似乎并不将每个2DGraphic变量识别为独立。

两张图片都会旋转到最后一张图片.'rotate'角。我在网上查了一下,但是每个参考旋转图形的教程都只处理一个图像。这很好用。我只是不能让两个图像旋转不同。我希望P1GFX与P2GFX分开旋转。

这是代码。 这个代码可以工作,但它们可以旋转到最后一个.rotate指定的内容。

public void paintComponent(Graphics frogp1) {


            Graphics2D P1GFX = (Graphics2D)frogp1;
            Graphics2D P2GFX = (Graphics2D)frogp1;
            P1GFX.rotate(90, 150 / 2, 150 / 2);
            P2GFX.rotate(40, 50, 50);
            P1GFX.drawImage(p1.getImage1(), p1x, p1y,this);
            P2GFX.drawImage(p2.getImage2(), p2x, p2y, this);


}

所以,我尝试在paintComponent中创建多个参数!这应该工作正常吗?不! 这个代码根本不显示图像!当paintComponent中有多个参数时,屏幕上不会绘制任何内容!

public void paintComponent(Graphics frogp1, Graphics frogp2) {


            Graphics2D P1GFX = (Graphics2D)frogp1;
            Graphics2D P2GFX = (Graphics2D)frogp2;
            P1GFX.rotate(90, 150 / 2, 150 / 2);
            P2GFX.rotate(40, 50, 50);
            P1GFX.drawImage(p1.getImage1(), p1x, p1y,this);
            P2GFX.drawImage(p2.getImage2(), p2x, p2y, this);


}

所以我想,嘿!也许我需要制作多个paintComponent!好吧,当然,如果不重新创建我自己的repaint()方法实例,那是不可能的。

public void paintComponent1(Graphics frogp1) {
            Graphics2D P1GFX = (Graphics2D)frogp1;
            P1GFX.rotate(90, 150 / 2, 150 / 2);
            P1GFX.drawImage(p1.getImage1(), p1x, p1y,this);

}
public void paintComponent2(Graphics frogp2) {
            Graphics2D P2GFX = (Graphics2D)frogp2;
            P2GFX.rotate(90, 150 / 2, 150 / 2);
            P2GFX.drawImage(p2.getImage2(), p2x, p2y,this);

}

这使得repaint()不执行任何操作,因此不会绘制任何内容。

请帮助我旋转多个图像/ Graphics2D变量!

2 个答案:

答案 0 :(得分:0)

Graphics2D P1GFX = (Graphics2D)frogp1;
Graphics2D P2GFX = (Graphics2D)frogp1;

转换对象意味着您仍在使用相同的Object引用。

如果您需要两个单独的Graphics对象,则需要执行以下操作:

Graphics2D p1gfx = (Graphics2D)frogp1.create();
Graphics2D p2gfx = (Graphics2D)frogp1.create();

然后当您使用Graphics对象时:

p1gfx.dispose();
p2gfx.dispose();

我更改变量名称以遵循Java命名约定。不要将所有大写字符用于变量名称。

答案 1 :(得分:0)

您可以旋转,然后取消旋转并重新定位:

public void paintComponent(Graphics graphics) {
        Graphics2D g2d = (Graphics2D)graphics;
        g2d.rotate(90, 150 / 2, 150 / 2);
        g2d.drawImage(p1.getImage1(), p1x, p1y,this);
        g2d.rotate(-90, 150 / 2, 150 / 2);
        g2d.rotate(40, 50, 50);
        g2d.drawImage(p2.getImage2(), p2x, p2y, this);
}