gpt4 book ai didi

java - 重复矩形而不是移动动画

转载 作者:行者123 更新时间:2023-11-30 05:52:43 25 4
gpt4 key购买 nike

这是我的代码!

package softwarea1;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Leo
*/
//534
public class Simulation extends JPanel implements ActionListener
{
DataModels dm;
Timer tm = new Timer(20, this);
private int velX = 2;
private int a = 0;

public void create()
{

Simulation sm = new Simulation(dm);
JFrame simulation = new JFrame();
simulation.setTitle("Traffic light and Car park Siumulation");
simulation.setSize(600,600);
simulation.setResizable(false);
simulation.setVisible(true);
simulation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
simulation.add(sm);
}
public void paintComponent(Graphics g)
{



// Moving Rectangle
g.setColor(Color.RED);
g.fillRect(a ,300, 1 ,30);
tm.start();
}
@Override
public void actionPerformed(ActionEvent e) {
a += velX;
repaint();
}


}

主类在这里:

 public class StartProj {
public static void main(String[] args) {
DataModels dm = new DataModels();
Simulation sm = new Simulation(dm);
sm.create();

}
}

我尝试为框架中的矩形设置动画,但它会重复多个矩形。怎么了?帮我?我还有一些类(class),但没有必要。非常感谢

最佳答案

你的 paintComponent(...)方法需要在第一行调用super的方法:

public void paintComponent(Graphics g)
{
super.paintComponent(g); // **** add this
// Moving Rectangle
g.setColor(Color.RED);
g.fillRect(a ,300, 1 ,30);
// tm.start(); // **** get rid of this.
}

这很重要,因为 super 方法会重新绘制组件的背景,而这是删除旧矩形所必需的。

此外,您在该方法内部有程序逻辑,您可以从内部启动一个 Swing 计时器,这是永远不应该做的事情。而是找一个更好、更可控的地方来启动你的计时器。

关于java - 重复矩形而不是移动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com