如何在Java GUI中使用计时器重复更改圆圈的颜色? [英] How to repeatedly change colors of a circle using a timer in a Java GUI?
问题描述
我正在尝试使用Java GUI创建交通灯,其中它仅显示一个圆圈,并且将颜色从红色,黄色更改为绿色.应该有一个计时器,并且三秒钟之内只有黄色会变成绿色.我已经设置了一个圆圈和一个红色,但是我无法使用计时器将其分别更改为黄色和绿色.
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 yellow should be changing to green within 3 seconds. I have set up a circle and a colour red, but I am unable to change it to the colours yellow, and green respectively using a timer.
顺便说一句,我确实是GUI的新手,虽然我仍然观看了一些youtube视频,但没有发现任何有用的信息或与此任务相关的信息,但我在网上找不到有用的资源.任何帮助将不胜感激!
代码:
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
public class Main extends Canvas {
public static void main(String[] args) {
JFrame frame = new JFrame();
Canvas canvas = new Main();
canvas.setSize(700, 700);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(200, 200, 300, 300);
}
}
预期输出:
https://www.youtube.com/watch?v=8dn-_3t3XQE
注意:它只能是一个圆圈,但其行为应与预期输出中的一个圆圈相同.
推荐答案
这是一种方法.指示灯保持亮起3秒钟.要更改其持续时间,必须相应地修改代码.这将在计时器内部完成.
Here is one approach. The lights stay on for 3 seconds. To change their duration the code must be modified accordingly. This would be done inside the timer.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TrafficLight extends JPanel {
JFrame frame = new JFrame();
int colorIdx = 0;
Color[] colors = { Color.green, Color.yellow, Color.red };
public static void main(String[] args) {
// Ensure the program is started on the Event Dispatch Thread
SwingUtilities.invokeLater(() -> new TrafficLight().start());
}
public void start() {
// set up
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the preferred size. Okay in this instance but best
// practice dictates to override getPreferredSize()
setPreferredSize(new Dimension(500, 500));
frame.add(this);
frame.pack();
// center on screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer t = new Timer(3000, ae -> {
colorIdx = colorIdx >= 2 ? 0 : colorIdx + 1;
repaint();
});
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colors[colorIdx]);
g.fillOval(150, 150, 200, 200);
}
}
这篇关于如何在Java GUI中使用计时器重复更改圆圈的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!