所以我讀到 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);
}
}
uj5u.com熱心網友回復:
您需要創建一個main方法,在其中創建一個新物件,在該實體中Thread傳遞 Runnable 類(即,Frame在您的情況下) ,然后傳遞. 見下文:ThreadstartThread
public class Main
{
public static void main(String args[])
{
Game g = new Game();
Label l = new Label(g);
Frame f = new Frame(l, g);
Thread t1 =new Thread(f);
// this will call run() method in Frame class
t1.start();
}
}
編輯:此外,您的 Frame 類應如下所示。一個執行緒執行一次它的run方法,然后它被認為是完成的。如果你想回圈,你必須自己做(下面while(true)使用了a,可以更改為一些false你希望程式退出時可以轉向的變數)。最后,一定要呼叫repaint()aftergame.update()使繪圖生效。
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame implements Runnable{
Game game;
Label label;
public Frame(Label label, Game game) {
this.label = label;
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);
}
@Override
public void run(){
while(true) {
game.update();
label.repaint();
try {
Thread.sleep(5);
}
catch(InterruptedException ex){}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/415684.html
標籤:
