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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21429246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:41:30  来源:igfitidea点击:

Java - How to move a rectangle that's drawn by Graphics2D?

javagraphics

提问by YayCoding

I'm trying to move a rectangle drawn by Graphics2D over, but it just doesn't work. When I do x += 1; It actually moves it 1 pixel over and stops. if I do say, x += 200; It moves it 200 pixels over ONCE not in every update, but ONCE.

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

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 is called outside void paint to make sure it's not incremented as 150 each time. Draws fine, just doesn't move, I tried using a thread and using a while loop so while the thread is running, it moves, but no luck.

int x 被称为 void paint 以确保它不会每次增加为 150。画得很好,只是不动,我尝试使用线程并使用 while 循环,因此当线程运行时,它会移动,但没有运气。

采纳答案by Paul Samsotha

Instead of using a while loop or a different thread, you should be using a java.swing.Timerfor animation. Here's the basic construct

您应该使用java.swing.Timerfor 动画,而不是使用 while 循环或不同的线程。这是基本结构

Timer(int delay, ActionListener listener)

where delay is the time you want to be delayed between repaints, and listeneris the listener with the callback function to perform. You could do something like this, where you change the xlocation, then call repaint();

其中 delay 是您希望在重绘之间延迟的时间,并且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();
            }
        });
    }
}

enter image description here

enter image description here

Here's a running example

这是一个运行示例

回答by VicDid

Use Affine Transformations. By simply using the AffineTransform class you can translate the graphics object along the screen on the x or y axis.

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

Here is a link with info on the class and its functions etc.: https://docs.oracle.com/javase/8/docs/api/java/awt/geom/AffineTransform.html

这是有关该类及其功能等信息的链接:https: //docs.oracle.com/javase/8/docs/api/java/awt/geom/AffineTransform.html

Here is another website that will give you examples on translation as well as other transformations: http://zetcode.com/gfx/java2d/transformations/

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

And when incrementing x or y to translate, you must call the repaint()function to repaint the graphics object.

并且当增加 x 或 y 进行平移时,您必须调用该repaint()函数来重新绘制图形对象。