展开全部
闪烁的原因请百度 swing 双缓冲
这里我只是给你一种简单的636f70793231313335323631343130323136353331333337396361解决办法:public class JoinDemo extends JFrame {
public static void main(String[] args) {
new JoinDemo();
}
private int x = 200, y = 300, r = 100;
private Graphics2D g2d;
private BufferStrategy bs;
public JoinDemo() {
this.setTitle("球车");
this.setSize(800, 600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.createBufferStrategy(2);
bs =this.getBufferStrategy();
g2d =(Graphics2D)bs.getDrawGraphics();
new UpdateThread().start();
}
public void draw() {
Image image = createImage(getWidth(), getHeight());
Graphics gg = image.getGraphics();
bufferedPaint(gg);
gg.dispose();
g2d.drawImage(image, 0, 0, null);
Stroke stroke=new BasicStroke(12.0f);
g2d.setStroke(stroke);
g2d.setColor(Color.green);
g2d.drawLine(0, 300, 800, 300);
g2d.drawLine(400, 0, 400, 600);
bs.show();
}
private void bufferedPaint(Graphics gg) {
gg.fillOval(x, y, r, r);
}
class UpdateThread extends Thread {
public void run() {
for (int j = 0; j <= 200; j++) {
x++;
draw();
sleep(10);
}
for (int j = 0; j <= 300; j++) {
y--;
draw();
sleep(10);
}
for (int j = 0; j <= 300; j++) {
y++;
draw();
sleep(10);
}
for (int j = 0; j <= 200; j++) {
x--;
draw();
sleep(10);
}
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
本文介绍了如何使用Java Swing通过创建BufferStrategy和双缓冲技术来解决组件闪烁问题。作者提供了一个示例代码,展示了如何在JoinDemo类中创建一个动态更新的圆形路径,避免了窗口刷新时的视觉抖动。

1325

被折叠的 条评论
为什么被折叠?



