gpt4 book ai didi

java - Graphics Context 只会在一个线程中绘制

转载 作者:行者123 更新时间:2023-12-01 18:00:35 25 4
gpt4 key购买 nike

我正在制作一个蛇游戏,但是每当我尝试在 draw() 方法中更新 Canvas 时,新的蛇都不会绘制。它在 run 线程中绘制。我尝试了很多不同的方法,但似乎无法让它发挥作用。

导入:

import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import java.io.*;
import java.util.*;
import javafx.scene.input.KeyEvent;
import javafx.event.EventHandler;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.*;
import javafx.scene.paint.*;
import javafx.scene.canvas.*;

实际类(class):

public class Snake extends Application implements Runnable
{
//Snake parts and locations
boolean dead;
int headX=0;
int headY=0;
// for the game
Group root = new Group();
Scene snakeG = new Scene(root, 550, 550,Color.BLACK);
final Canvas canvas = new Canvas(550,550);
GraphicsContext gc = canvas.getGraphicsContext2D();
//Start Game
VBox newGame = new VBox(3);
Scene startC = new Scene(newGame, 200, 200);
Label info = new Label("Snake Game \nCreated by: Austin");
Label rules = new Label("Rules\n1.) If you hit the edge you die\n2.) If you touch your snake you die\n3.)Collect fruit to increase your snakes size");
Button startBut = new Button("Start Game");
Stage startS;

public static void main ( String[] args )
{
launch(args);
}

@Override
public void start ( Stage primaryStage )throws Exception
{
startS=primaryStage;
startS.setTitle("Snake");
newGame.getChildren().addAll(info,rules,startBut);
newGame.setAlignment(Pos.CENTER);
startS.setScene(startC);
startS.show();

startBut.setOnAction(e ->
{
startGame();
});
}

public void startGame()
{
System.out.println("Success");
headX=275;
headY=275;
dead = false;
gc.clearRect(0,0,800,800);
startS.setScene(snakeG);
gc.setFill(Color.GREEN);
gc.fillRect(headX,headY,10,10);
root.getChildren().add(canvas);
(new Thread ( new Snake())).start();
}

public void run()
{
draw();
}

// draws the snake
public void draw()
{
System.out.println("DRAW STARTED");
gc.setFill(Color.GREEN);
gc.fillRect(50,50,10,10);
}
}

如果您知道在 JavaFX 中绘制图形的更好方法,请告诉我。这是我能为我正在做的事情找到的唯一方法。

最佳答案

您的方法存在一些问题。

  1. 您不需要自己的线程。
  2. 您只能使用 JavaFX 线程修改 Activity 场景图(包括 Canvas )。阅读JavaFX concurrency documentation :

    The JavaFX scene graph, which represents the graphical user interface of a JavaFX application, is not thread-safe and can only be accessed and modified from the UI thread also known as the JavaFX Application thread.

  3. 您的主应用程序类不应实现 Runnable

一些建议:

  1. 您可能会发现为游戏对象使用 SceneGraph 节点比使用 Canvas 更容易,但两者都应该可以。
  2. 您可以实现您的game loop使用AnimationTimerdemoed here .
  3. 这是 using an AnimationTimer for display 的示例.

关于java - Graphics Context 只会在一个线程中绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274078/

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