我对图形和 japplet 很陌生,我制作了一个横跨屏幕的矩形。但由于某种原因,它只是画一条线,而不会在移动后删除矩形的旧实例。
主要:
public class Main extends JApplet implements Runnable {
private static final long serialVersionUID = 1L;
private static int width = 900;
private static int height = 600;
public static int fps = 60;
public Thread thread = new Thread(this);
public static Ailoid ailoid = new Ailoid();
public void init() {
setSize(width, height);
setBackground(Color.white);
ailoid.setLocation(new Location(100, 100));
AlienManager.registerAlien(ailoid);
}
public void paint(Graphics g) {
g.setColor(Color.green);
for (Alien alien : AlienManager.getAliens()) {
Location loc = alien.getLocation();
int x = loc.getX();
int y = loc.getY();
g.fillRect(x, y, 10, 20);
}
}
// Thread start
@Override
public void start() {
thread.start();
}
// Thread stop
@SuppressWarnings("deprecation")
@Override
public void destroy() {
thread.stop();
}
@Override
public void run() {
while (true) {
Updater.run();
repaint();
try {
// 1000 divided by fps to get frames per millisecond
Thread.sleep(1000 / fps);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
更新者:
public class Updater {
public static void run() {
for (Alien alien : AlienManager.getAliens()) {
Location loc = alien.getLocation();
int x = loc.getX();
int y = loc.getY();
alien.setLocation(new Location(x, y));
}
}
}
为什么它不删除旧图形?谢谢!
最佳答案
您的主要问题是您的 paint(...)
方法没有调用 super 方法,该方法允许组件重绘其内容:
public void paint(Graphics g) {
super.paint(g);
//....
话虽如此,最好不要在顶级窗口中进行绘制,而是在小程序显示的 JPanel 的 paintComponent
方法中进行绘制。如果您执行此更正,则执行相同的操作 - 调用 super 方法。
class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//....
顺便说一句,这段代码:
public class Updater {
public static void run() {
for (Alien alien : AlienManager.getAliens()) {
Location loc = alien.getLocation();
int x = loc.getX();
int y = loc.getY();
alien.setLocation(new Location(x, y));
}
}
}
看起来它并没有对事情产生太大的影响。事实上,根据这段代码,你的外星人应该保持完全静止。
编辑
另外,这是永远的代码,您永远不应该在应用程序中使用这些代码:
@SuppressWarnings("deprecation")
@Override
public void destroy() {
thread.stop();
}
线程的 stop()
方法已被弃用并且永远不应该被调用,这是有原因的。如果您想知道原因,请查看 API。
关于Java JApplet 在移动旧矩形后不会将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706812/