How to repeatedly change colors of a circle using a timer in a Java GUI?

后端 未结 2 1134
[愿得一人]
[愿得一人] 2021-01-27 02:52

I am trying to create a traffic light using a Java GUI, where it displays only one circle and it changes colours from red, to yellow, to green. There should be a timer and only

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 03:37

    1. Don't extend Canvas. Custom painting in Swing is done by extending JPanel and by overriding the paintComponent() method. Read the section from the Swing tutorial on Custom Painting for more information and working examples.

    2. A painting method should only paint the current state of the class. So you would need to add a method like setLightColor(Color lightColor) to your component that does the custom painting. Then in the painting method you use that value for the Color of your circle (instead of hard coding "RED"). Or you have a method like changeLight() that updates a varable from 0, 1, 2, 0, 1, 2... . Then in the painting method you you check the state of the variable and paint the appropriate color.

    3. You need to use a Swing Timer to schedule an event. When the Timer fires you invoke the setLightColor(...) method on your class.

    4. The Timer should be part of your class that does the custom painting. You should have a method that can start/stop the Timer.

    You can check out: https://stackoverflow.com/a/7816604/131872 for a basic example of the Swing Timer.

提交回复
热议问题