【发布时间】:2022-01-16 11:12:07
【问题描述】:
所以我读到 Runnable 接口中的 run 函数会自动调用,但它对我不起作用(未调用 run)。这是我第一次在 java 中做任何事情,所以我可能做了一些愚蠢的事情。下面的代码应该在屏幕上移动一个矩形。矩形已绘制,但没有移动。
主要:
public class Label extends JLabel{
Game game;
public Label(Game game){
this.game = game;
}
public void paint(Graphics gfx){
game.render(gfx);
}
}
框架:
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame implements Runnable{
Game game;
public Frame(Label label, Game game) {
this.setSize(600, 600);
this.setTitle("idk");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setEnabled(true);
this.game = game;
this.setContentPane(label);
}
public void run(){
game.update();
try {
Thread.sleep(20);
}
catch(InterruptedException ex){}
}
}
标签:
import javax.swing.*;
import java.awt.*;
public class Label extends JLabel{
Game game;
public Label(Game game){
this.game = game;
}
public void paint(Graphics gfx){
game.render(gfx);
}
}
游戏:
import java.awt.*;
public class Game {
float x = 0;
float y = 0;
float w = 20;
float h = 20;
void render(Graphics gfx){
gfx.fillRect((int)x, (int)y, (int)w, (int)h);
}
void update(){
x += 0.1f;
System.out.println(x);
}
}
【问题讨论】:
-
可运行的 JLabel 没有任何意义。
-
@Olivier 我更改了代码以使 JFrame 可运行,但结果仍然相同。矩形被绘制但不移动。我更新了问题中的代码
-
"Runnable接口的run函数被自动调用"错了。
-
请发布minimal reproducible example,包括
main方法。对于 Swing 动画,使用摇摆 Timer -
通常,在 Swing 中,当您想要自己进行绘画时,您会编写一个扩展
javax.swing.JPanel的类并覆盖其paintComponent方法。请参阅Performing Custom Painting。如果要添加动画,通常使用 [Swing] 计时器。参考How to Use Swing Timers。