我有一些为了好玩而编写的代码,用不同颜色绘制圆圈线。在不使用 Swing Timer 的情况下,圆圈会“一次性”绘制,并且它们的颜色会在红色、绿色、蓝色和黄色之间交替。因此,如果没有计时器,代码将按预期工作。然而,当我尝试制作动画以便可以看到正在绘制的圆圈时,这意味着使用 Swing Timer 进行循环而不是 while/for 循环,所有圆圈都具有相同的颜色,并保持四种颜色一起闪烁。我想问题是颜色与每个对象无关,而是与整个框架相关联,因为我每隔几毫秒更改一次框架的颜色,已经绘制的圆圈不会像它们那样保留其原始颜色while 循环。如果您看到任何解决方案,我们将不胜感激!
public class Board extends JPanel {
private static final long serialVersionUID = 6676924870723702476L;
private Timer timer;
private final int DELAY = 30;
private ActionListener drawLine;
private Ellipse2D circ;
private ArrayList<Ellipse2D> circles = new ArrayList<>();
private double circDiam = 80;
private double circX = 0;
private double circY = 0;
private short circNum = 1;
public Board() {
drawLine = (ActionEvent e) -> {
repaint();
circX += circDiam;
if(circNum == 5)
{
circNum = 1;
}
};
timer = new Timer(DELAY, drawLine);
timer.start();
}
private Color getCircColor(short circNum) {
switch(circNum) {
case 1:
return Color.blue;
case 2:
return Color.red;
case 3:
return Color.yellow;
case 4:
return Color.green;
default:
return Color.gray;
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = new Dimension(getWidth(), getHeight());
double width = size.getWidth();
double height = size.getHeight();
Graphics2D g2d = (Graphics2D) g;
RenderingHints rHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rHints);
青春有我
慕田峪4524236
相关分类