Cao*_*ong 2 java swing paintcomponent
这是我的代码!
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();
}
}
Run Code Online (Sandbox Code Playgroud)
主要类别:
public class StartProj {
public static void main(String[] args) {
DataModels dm = new DataModels();
Simulation sm = new Simulation(dm);
sm.create();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试动画帧中的矩形,但它重复多个矩形.怎么了?帮我?我有更多的课,但他们没有必要.非常感谢你
你的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.
}
Run Code Online (Sandbox Code Playgroud)
这很重要,因为super方法重新绘制了组件的背景,这是擦除旧矩形所必需的.
此外,你在这个方法中有程序逻辑,你从内部启动一个Swing Timer,这是永远不应该做的事情.而是找到一个更好的更可控的地方来启动你的Timer.
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |