能不能请各位帮小弟看一下,为什么我用了双缓冲技术后仍然闪屏现象严重?

it小小白痴 2019-05-21 11:41:03

package com.Test;

import javax.swing.JApplet;
import javax.swing.JButton;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.util.Vector;
import java.awt.event.ActionEvent;

class Ball
{
final int max_speed = 5; //小球最大速度
final int radius = 30; //小球半径
final int height = 380, width = 450; //运动区域的高度和宽度
int x = (int)(Math.random() * (width - radius)); //初始横坐标
int y = (int)(Math.random() * (height - radius)); //初始纵坐标
int dx = (int)(Math.random() * max_speed), dy = (int)(Math.random() * max_speed); //坐标改变值

public void run()
{
if (width - radius - x - dx < 0 || x + dx - radius < 0) //判断越界
{
dx = -dx;
}
if (height - radius - y - dy < 0 || y + dy - radius < 0)
{
dy = -dy;
}

//运动过程
x += dx;
y += dy;
}
}

public class Collision_Ball extends JApplet implements Runnable
{
final int height = 450, width = 450; //界面大小
Vector<Ball> balls = new Vector<Ball>(); //所有小球

//常用颜色集合
Color[] popular = {Color.BLACK, Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.RED, Color.YELLOW};
Image offScreen = null;

public void paint(Graphics g)
{
super.paint(g); // 轻量级组件不调用update
for (int i = 0; i < balls.size(); i++)
{
g.setColor(popular[i % popular.length]); //按顺序取一个颜色
g.fillOval(balls.elementAt(i).x,
balls.elementAt(i).y,
balls.elementAt(i).radius,
balls.elementAt(i).radius);
balls.elementAt(i).run();
// ball.print=true;
}
}

public void update(Graphics g) //双缓冲技术
{
if (offScreen == null)
{
offScreen = createImage(width, height);
}
Graphics gOffScreen = offScreen.getGraphics();
paint(gOffScreen);
g.drawImage(offScreen, 0, 0, null);
}

public Collision_Ball()
{
init();
}

Thread my_applet = null;

public void init()
{
getContentPane().setLayout(null);
getContentPane().setBounds(0, 0, width, height);
JButton button = new JButton("\u6DFB\u52A0\u5C0F\u7403");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
balls.addElement(new Ball()); //按下按钮就增加一个新球
repaint();
// balls.elementAt(balls.size()-1).start();
}
});
final int x = 0, y = 380;
button.setBounds(x, y, width - x, height - y);
button.setFont(new Font("微软雅黑", Font.PLAIN, 20));
getContentPane().add(button);

my_applet = new Thread(this);
my_applet.start();
}

@Override
public void run()
{
while (true)
{
if (!balls.isEmpty()) //如果还有小球就开始运动
{
repaint();
try
{
Thread.sleep(5);
}
catch (InterruptedException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}

public void start()
{

}

public void stop()
{
balls.clear();
}
}
...全文
22 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧