java 2D绘画出现闪屏问题~~急
用java 2D绘图,用Image 载入图片,发觉屏幕闪动。之后在网上查资料,发现可以用BufferedImage实现图片双缓冲。但是我实现之后,效果还是一样。
之后干脆把图片去掉。直接画直线跟圆,让圆运动(利用线程控制住时间),可是依旧出现闪屏现象。如此便纠结了。
发觉,应该是线程调用了repaint()重绘方法。知道调用repaint()会自动调用paint()—>update()-->paint(),问题出现在update上,可是,重写update()没头绪。希望高手指点一下。
<java code>
package drawing;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
public class Ball extends JFrame {
int coordinateX =10,coordinateY = 344;
int LineCX =224,LineCY = 170;
int on_off = 0;
int on_off_Line = 2;
int values = 1;
int openLight =0;
final String message1 = "1";
final String message0 = "0";
int messageGo = 0;
String m = "O";
Thread thread = new Thread();
Image light,light3;
Graphics2D g2d;
Thread autoThread;
boolean running = false;
public Ball(){
super("仿造电路"); //调用父类构造函数
setSize(800,700); //设置窗口尺寸
setBackground(Color.cyan);
setVisible(true); //设置窗口可视
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
light3 = Toolkit.getDefaultToolkit().getImage("D:\\Program Files\\VC++6.0\\eclipse-java-indigo-SR2-win32\\eclipse\\workspace\\draw\\src\\DH\\电路灯.gif");
light = Toolkit.getDefaultToolkit().getImage("D:\\Program Files\\VC++6.0\\eclipse-java-indigo-SR2-win32\\eclipse\\workspace\\draw\\src\\DH\\red_blue1.gif");
}
public void paint(Graphics g){ //绘制组件方法
g2d=(Graphics2D)g;
Dimension dim = this.getSize();
g2d.setColor(Color.white); //设置绘制颜色为白色
g2d.fillRect(0, 0, dim.width, dim.height);
g2d.setStroke(new BasicStroke(4));//设置线条粗细
g2d.setColor(Color.black); //设置绘制颜色
g2d.drawRoundRect(46,343,14,14,14,14); //开始的小圆圈
g2d.draw(new Line2D.Double(220, 490,240,490));//小横线
g2d.drawString(m, coordinateX, coordinateY);
BallThread b = new BallThread();
b.start();
}
class BallThread implements Runnable {
public void start(){
if(autoThread == null){
autoThread = new Thread(this);
autoThread.start();
}
}
@Override
public void run() {
Thread currentThread = Thread.currentThread();
while(autoThread == currentThread){
try{
Thread.sleep(5);
}catch(InterruptedException e){
e.printStackTrace();
}
if(coordinateX<190){
coordinateX=coordinateX+4;
}
if(coordinateX==190){
stop();