gpt4 book ai didi

java - 线程动画示例不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:18 25 4
gpt4 key购买 nike

我试图遵循这些教程 http://zetcode.com/tutorials/javagamestutorial/animation/该页面上的三个示例似乎都不适合我。其中一种使用 Swing 计时器,一种使用实用计时器,最后一种,据认为是最有效和最准确的,根据页面使用线程来制作动画。

我将向您展示使用线程的方法,因为我认为在使用动画制作游戏时我会采用这种方式。

ThreadAnimationExample.java(在教程中它被称为 star.java,但显然这不起作用)

import java.awt.EventQueue;
import javax.swing.JFrame;

public class ThreadAnimationExample extends JFrame {

public ThreadAnimationExample() {

add(new Board());

setTitle("Star");

pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
JFrame ex = new ThreadAnimationExample();
ex.setVisible(true);
}
});
}
}

Board.java(主类)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Board extends JPanel
implements Runnable {

private final int B_WIDTH = 350;
private final int B_HEIGHT = 350;
private final int INITIAL_X = -40;
private final int INITIAL_Y = -40;
private final int DELAY = 25;

private Image star;
private Thread animator;
private int x, y;

public Board() {

loadImage();
initBoard();
}

private void loadImage() {

ImageIcon ii = new ImageIcon("star.png");
star = ii.getImage();
}

private void initBoard() {

setBackground(Color.BLACK);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
setDoubleBuffered(true);

x = INITIAL_X;
y = INITIAL_Y;
}

@Override
public void addNotify() {
super.addNotify();

animator = new Thread(this);
animator.start();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

drawStar(g);
}

private void drawStar(Graphics g) {

Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(star, x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}

private void cycle() {

x += 1;
y += 1;

if (y > B_HEIGHT) {

y = INITIAL_Y;
x = INITIAL_X;
}
}

@Override
public void run() {

long beforeTime, timeDiff, sleep;

beforeTime = System.currentTimeMillis();

while (true) {

cycle();
repaint();

timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;

if (sleep < 0) {
sleep = 2;
}

try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}

beforeTime = System.currentTimeMillis();
}
}
}

最佳答案

如果您使用 Eclipse,您应该创建一个源文件夹并将该图像添加到源文件夹中。然后你可以使用这个:

ImageIcon ii = new ImageIcon( getClass().getResource("/imageName.png") );

关于java - 线程动画示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23649584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com