关于Swing中repaint的一点问题

直接对一个JFrame进行repaint的话,会出现屏幕闪烁或者不能显示屏幕的问题

如下代码


import javax.swing.*;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class S2P11 extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	final int WIDTH = 900, HEIGHT = 650;
	double p1Speed = .5, p2Speed = .5;
	
	/************************************************/
	final int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3;
	int p1Direction = UP;
	int p2Direction = UP;
	/************************************************/
	
	
	Rectangle p2 = new Rectangle(WIDTH/9 + (int)(WIDTH/9*1.5/2), (HEIGHT/2) + (HEIGHT/10), WIDTH/30, WIDTH/30);
	Rectangle p1 = new Rectangle(WIDTH/9, HEIGHT/2, WIDTH/30, WIDTH/30);
	
	public S2P11() {
		super("Radical Racing");
		setSize(WIDTH/9*10, HEIGHT/9*10);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		setVisible(true);
		new Thread()
		{
			public void run() {while(true)
			{
				while(true)
					{
					repaint();
					 p2.y+=10;
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
			}};
		}.start();
	}
		
		public void paint(Graphics g){
			super.paint(g);
			Graphics2D g2d=(Graphics2D)g;
			g2d.setColor(Color.DARK_GRAY);
			g2d.fillRect(0, 0, WIDTH, HEIGHT);
			g2d.setColor(Color.red);
			g2d.fill3DRect(p2.x, p2.y, p2.width, p2.height,true);
	}
		

			
			
		/************************************************/
	
	public static void main(String[] args) {
		new S2P11();
		
	}

}

 所以如果我们要更新显示的内容  不要直接对Frame刷新 而是在JFrame上添加JPanel  然后对JPanel刷新

你可能感兴趣的:(关于Swing中repaint的一点问题)