java - 如何在 Java 中旋转屏幕组件?

标签 java swing graphics2d paintcomponent

 import javax.swing.*;
 import java.awt.*;

 public class JFrameAnimationTest extends JFrame {
     public static void main(String[] args) throws Exception{
        AnimationPanel animation = new AnimationPanel();
        JFrameAnimationTest frame = new JFrameAnimationTest();
        frame.setSize(600, 480);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(animation);
        frame.setVisible(true);        
        for(int i = 0; i < 100; i++) {
            animation.incX(1);
            //animation.incY(1);
            animation.repaint();
            Thread.sleep(10);
        }
    }
}

class AnimationPanel extends JPanel {

    int x = 10;
    int y = 10;   

  public AnimationPanel() {        
  }

  @Override
  protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.setColor(Color.BLUE);
      g.drawRect(x, y, 20, 20);
      g.fillRect(x, y, 20, 20);
  }

  protected void incX(int X) {
      x += X;
  }

  protected void incY(int Y) {
      y += Y;
  }
}

无论如何,这是我的代码。它可能看起来有点困惑,因为我还不习惯 stackoverflow,所以我很抱歉。

这是我的问题:这个程序让这个小矩形慢慢向右移动;如何在该时间段内为矩形运动添加旋转?

最佳答案

注意:我实际上还没有编译此代码,但您已经明白了要点。

public void paintComponent( Graphics g )
{
    super.paintComponent( g );
    Graphics2D g2d = (Graphics2D) g;

    // The 20x20 rectangle that you want to draw
    Rectangle2D rect = new Rectangle2D.Double( 0, 0, 20, 20 );

    // This transform is used to modify the rectangle (an affine
    // transform is a way to do operations like translations, rotations,
    // scalings, etc...)
    AffineTransform transform = new AffineTransform();

    // 3rd operation performed: translate the rectangle to the desired
    // x and y position
    transform.translate( x + 10, y + 10 );

    // 2nd operation performed: rotate the rectangle around the origin
    transform.rotate( rotation );

    // 1st operation performed: translate the rectangle such that it is
    // centered on the origin
    transform.translate( -10, -10 );

    // Apply the affine transform
    Shape s = transform.createTransformedShape( rect );

    // Fill the shape with the current paint
    g2d.fill( s );

    // Stroke the edge of the shape with the current paint
    g2d.draw( s );
}

另请注意,当您修改 xy 时,您确实应该使用 javax.swing.Timer 之类的东西>旋转以及当您调用repaint()时。这样所有的事情都发生在事件调度线程上。

关于java - 如何在 Java 中旋转屏幕组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12852076/

相关文章:

java - 使用 JApplet 连接到 SQL

java - 创建后如何在 JTextField 中设置新文本?

java - 根据设计分辨率生成当前屏幕分辨率的正确坐标

java - 每秒而不是立即执行和显示图形

java - 代码有时有效但有时无效(内存或线程问题)

Java 图形2D;切换我拥有的形状对象的绘制顺序?

java - JComponent 不会显示图像

java.io.IOException : Attempted read from closed stream 异常

java - 同步重叠的方法集

java - 将 JSONWithPadding (Jersey) 与替代 mime 类型结合使用