1 回答
TA贡献1946条经验 获得超4个赞
好吧,我会做两件不同的事情:首先,我测试了两个版本,但都对我不起作用。我想这可能是由您在构造函数中创建的无限循环引起的,因为它永远不会退出。
除此之外,您的 paintMethod 似乎有错误(实际上应该是绘制并覆盖 JPanel 中的 super 方法),您需要对更新进行更改。我建议您看一下“Game-Loops”,尽管它也可以为每个实例使用单独的线程,但我建议不要这样做。我更正了您的代码,以便您可以查看它:具有单独线程的第一个版本:
package stackoverflowtests;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Skeleton extends JPanel implements Runnable {
private BufferedImage img = null;
public Skeleton() {
setSize(1000, 500);
try {
img = ImageIO.read(new File("index.jpg"));
} catch (IOException e) {
System.out.println("Loading failed.");
}
}
public void paint(Graphics g) {
g.drawImage(img, 50, 50, null);
}
@Override
public void run() {
while (true) repaint();
}
}
主要是这样的:
package stackoverflowtests;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
setSize(1280, 720);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Skeleton skeli = new Skeleton();
skeli.setLocation(0, 0);
skeli.setSize(1000, 500);
add(skeli);
new Thread(skeli).start();
setVisible(true);
}
public static void main(String[] args) {
Main main = new Main();
}
}
游戏循环的可能性 2:
package stackoverflowtests;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Skeleton extends JPanel {
private BufferedImage img = null;
public Skeleton() {
setSize(1000, 500);
try {
img = ImageIO.read(new File("index.jpg"));
} catch (IOException e) {
System.out.println("Loading failed.");
}
}
public void paint(Graphics g) {
g.drawImage(img, 50, 50, null);
}
}
主要是:
package stackoverflowtests;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
setSize(1280, 720);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Skeleton skeli = new Skeleton();
skeli.setLocation(0, 0);
skeli.setSize(1000, 500);
add(skeli);
setVisible(true);
}
public static void main(String[] args) {
Main main = new Main();
// Gameloop
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (true) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
// updates++;
delta--;
}
System.out.println("repaint");
main.repaint();
frames++;
}
}
}
您需要问自己的第二件事是,您是否可以为每个实体使用 BufferedImage 对象而不是整个 JPanel ;)
添加回答
举报