Java – 如何移动由Graphics2D绘制的矩形?

我试图移动Graphics2D绘制的矩形,但它不起作用。 当我做x + = 1; 它实际上将它移动1个像素并停止。 如果我说,x + = 200; 它在ONCE上移动200像素而不是每次更新,而是ONCE。

public void paint(Graphics g) { super.paint(g); g.setColor(Color.WHITE); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(Color.RED); g.fillRect(x, 350, 50, 50); x += 1; } 

int x在void paint外部调用,以确保它每次都不会增加为150。 绘制正常,只是不动,我尝试使用线程并使用while循环,所以当线程运行时,它移动,但没有运气。

您应该使用java.swing.Timer进行动画,而不是使用while循环或其他线程。 这是基本结构

 Timer(int delay, ActionListener listener) 

其中延迟是您希望在重新绘制之间延迟的时间,并且listener是具有要执行的回调函数的侦听器。 你可以做这样的事情,你改变x位置,然后调用repaint();

  ActionListener listener = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (x >= D_W) { x = 0; drawPanel.repaint(); } else { x += 10; drawPanel.repaint(); } } }; Timer timer = new Timer(250, listener); timer.start(); 

 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyBindings extends JFrame { private static final int D_W = 500; private static final int D_H = 200; int x = 0; int y = 0; DrawPanel drawPanel = new DrawPanel(); public KeyBindings() { ActionListener listener = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (x >= D_W) { x = 0; drawPanel.repaint(); } else { x += 10; drawPanel.repaint(); } } }; Timer timer = new Timer(100, listener); timer.start(); add(drawPanel); pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } private class DrawPanel extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.GREEN); g.fillRect(x, y, 50, 50); } public Dimension getPreferredSize() { return new Dimension(D_W, D_H); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { new KeyBindings(); } }); } } 

在此处输入图像描述

这是一个运行的例子

使用仿射变换。 通过简单地使用AffineTransform类,您可以在x或y轴上沿着屏幕平移图形对象。

这是一个关于类及其function等信息的链接: https : //docs.oracle.com/javase/8/docs/api/java/awt/geom/AffineTransform.html

这是另一个网站,它将为您提供有关翻译和其他转换的示例:http: //zetcode.com/gfx/java2d/transformations/

当递增x或y以进行转换时,必须调用repaint()函数来重新绘制图形对象。