Change javafx circles color in certain time using multithreads

前端 未结 3 534
情深已故
情深已故 2021-01-27 18:45

I am creating traffic light simulator with javafx that changes colour in every 2 seconds (first red light blinks and remain for 2 seconds) using the concept of multithreading. I

3条回答
  •  面向向阳花
    2021-01-27 19:19

    I was so confused on how to make this work honestly I agree with Sedrick check out the JavaFX Animation class but I was bored so I made this work also there is definitely better ways to do this but I did my best to try and keep as much code as possible because you wanted to lean from this. Just looked at this again its p̶r̶e̶t̶t̶y̶ ̶m̶u̶c̶h̶ only the variable names lol

    public class Main extends Application {
    
        private Circle circle;
        private Circle circle1;
        private Circle circle2;
        private HashMap colorHashMap = new HashMap<>();
        private HashMap counterHashMap = new HashMap<>();
    
        @Override
        public void start(Stage stage) {
            circle = new Circle(15, 15,30, Color.GREEN);
            colorHashMap.put(circle,Color.GREEN);
            counterHashMap.put(circle, 3);//Start On
    
            circle1 = new Circle(15, 45,30, Color.GREY);
            colorHashMap.put(circle1,Color.YELLOW);
            counterHashMap.put(circle1, 2);
    
            circle2 = new Circle(15, 60,30, Color.GREY);
            colorHashMap.put(circle2,Color.RED);
            counterHashMap.put(circle2, 1);
    
            VBox vBox = new VBox();
            vBox.getChildren().addAll(circle,circle1,circle2);
    
            Scene scene = new Scene(vBox);
            stage = new Stage();
            stage.setScene(scene);
            stage.show();
    
            try {
                startThreads();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        private void startThreads() throws InterruptedException {
            new Thread(()->{
                while (true) {
                    flipColor(circle);
                    flipColor(circle1);
                    flipColor(circle2);
    
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
        private void flipColor(Circle circle){
            if(counterHashMap.get(circle)%3==0) {
                Platform.runLater(()->circle.setFill(colorHashMap.get(circle)));
                counterHashMap.put(circle,1);
            }
            else {
                if(!circle.getFill().equals(Color.GREY))
                    Platform.runLater(()->circle.setFill(Color.GREY));
                counterHashMap.put(circle,counterHashMap.get(circle)+1);
            }
    
        }
    
        public static void main(String[] args) { launch(args); }
    }
    

提交回复
热议问题