Java 帮助!油漆组件的困境

问题描述 投票:0回答:2

我是 Java 新手,每天都在学习新东西。 我正在尝试学习如何获取两个不同的 .png 文件并使用绘画组件分别旋转它们。 我能够使两个图像都绘制并具有单独的运动,但是旋转函数似乎无法将每个 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 变量!

java swing rotation paintcomponent
2个回答
0
投票
Graphics2D P1GFX = (Graphics2D)frogp1;
Graphics2D P2GFX = (Graphics2D)frogp1;

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

如果你想要两个独立的 Graphics 对象,那么你需要这样做:

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

然后当您完成使用的 Graphics 对象时:

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

我更改了变量名称以遵循 Java 命名约定。不要使用全部大写字符作为变量名称。


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);
}
© www.soinside.com 2019 - 2024. All rights reserved.