java上移动,Java在屏幕上移动对象
我正試圖在我的
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);
}
最佳答案 這是一個用搖擺做的小演示.只需用火車圖像替換黑色矩形就可以了.
訣竅是使用單獨的線程(或計時器)來進行動畫循環(通常稱為游戲循環).循環僅告訴窗口重繪自己,并且在每次重繪時,首先計算動畫對象的新位置,然后繪制它們.
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;
}
}
總結
以上是生活随笔為你收集整理的java上移动,Java在屏幕上移动对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 丹参饮片的功效与作用、禁忌和食用方法
- 下一篇: 樱桃酒的功效与作用、禁忌和食用方法