Java 在屏幕上移动对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19629257/
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-12 18:57:05  来源:igfitidea点击:

Java Moving an Object Across the Screen

java

提问by Emmaline Smith

I am trying to move a train across my java window and am having serious problems. I have a Train class in which I made the train, and a Driver class which is supposed to move the train. I need to make the whole train move from right to left until it 'passes' the left edge of the screen. Then add an if statement to change the dx so the train restarts on the right side . The below is what I have tried but it is not working. Can anyone help me please??

我试图在我的 Java 窗口中移动一列火车,但遇到了严重的问题。我有一个火车班级,我在其中制造了火车,还有一个司机班级,应该移动火车。我需要让整个火车从右向左移动,直到它“通过”屏幕的左边缘。然后添加一个 if 语句来更改 dx,以便列车在右侧重新启动。以下是我尝试过但不起作用的方法。有人可以帮我吗??

public class Driver extends GraphicsProgram
{
    //~ Instance/static variables .............................................

    private static final int N_STEPS = 1000;
    private static final int PAUSE_TIME = 20;
    private static final double TRAIN_LENGTH = 320;

    //~ Constructor ...........................................................

    // ----------------------------------------------------------
    /**
     * The run() method of the Driver Class.
     * Creates an instance of the Train Class.
     * Responsible for animating the train across the screen.
     */
    public void run()
    {
        Train train = new Train(getGCanvas());
        for (int i = 0; i < N_STEPS; i++) {
            train.move(-100, 0);
            pause(PAUSE_TIME);
    }

回答by Aurelien Ribon

Here is a little demo made with swing. Just replace the black rectangle with an image of your train and you're done.

这是一个用swing制作的小演示。只需将黑色矩形替换为您的火车图像即可。

The trick is to use a separate thread (or timer) to do the animation loop (often called game loop). The loop only tells your window to redraw itself, and on each redraw, you first compute the new positions of the animated objects, then you draw them.

诀窍是使用单独的线程(或计时器)来执行动画循环(通常称为game loop)。循环只告诉你的窗口重绘自己,在每次重绘时,你首先计算动画对象的新位置,然后绘制它们。

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

public class TrainDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Train Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new TrainCanvas());
        frame.setVisible(true);
    }

}

class TrainCanvas extends JComponent {

    private int lastX = 0;

    public TrainCanvas() {
        Thread animationThread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    repaint();
                    try {Thread.sleep(10);} catch (Exception ex) {}
                }
            }
        });

        animationThread.start();
    }

    public void paintComponent(Graphics g) {
        Graphics2D gg = (Graphics2D) g;

        int w = getWidth();
        int h = getHeight();

        int trainW = 100;
        int trainH = 10;
        int trainSpeed = 3;

        int x = lastX + trainSpeed;

        if (x > w + trainW) {
            x = -trainW;
        }

        gg.setColor(Color.BLACK);
        gg.fillRect(x, h/2 + trainH, trainW, trainH);

        lastX = x;
    }

}

回答by Mars

color c = color(0); float x = 0; float y = 100; float speed = 1;
void setup() { size(200,200); }
void draw() { background(255); move(); display(); }
void move() { x = x + speed; if (x > width) { x = 0; } }
void display() { fill(c); rect(x,y,30,10); }