Forum Stats

  • 3,827,853 Users
  • 2,260,832 Discussions
  • 7,897,398 Comments

Discussions

Graphic disappear or froze

User_VEIKG
User_VEIKG Member Posts: 1 Green Ribbon

I made some simple stuff here when it runs it would take random points where it will freeze or disappear.

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;


public class Test extends Application {

    int screenWidth = 400;
    int screenHeight = 300;
    int pos1 = 0;
    boolean maxScreen = true;

    public void start(Stage stage){
        Group root = new Group();
        stage.setTitle("MultiThread");
        Scene scene = new Scene(root);
        Canvas canvas = new Canvas(screenWidth, screenHeight);
        root.getChildren().add(canvas);
        stage.setScene(scene);
        stage.show();
        GraphicsContext gc = canvas.getGraphicsContext2D();
        Thread t = new Thread(() -> animate(gc));
        t.start();
    }

    public void animate(GraphicsContext gc){

        while (true) {
            clearScreen(gc);
            drawSqure(gc);
            if(pos1 <= (350) && maxScreen == true){
                pos1++;
                if(pos1 == 350){
                    maxScreen = false;
                }
            }
            else{
                pos1--;
                if(pos1 ==0 ){
                    maxScreen = true;
                }
            }
            delay(1);
        }
    }

    void drawSqure(GraphicsContext gc){
        gc.setFill(Color.RED);
        gc.fillRect(pos1, 0, 50,50);
    }

    void clearScreen(GraphicsContext gc){
        gc.setFill(Color.WHITE);
        gc.fillRect(0,0, screenWidth,screenHeight);
    }

    public static void delay(int duration) {
        try {
            Thread.sleep(duration);
        } catch (InterruptedException ex) {
        }
    }

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

As you can see nothing special here I use IntelliJ as IDE, only graphic freeze not console any seen this problem before after searching around this does not seems like a general problem.