JPanel闪烁

时间:2015-10-01 17:24:11

标签: java swing

在Java应用程序中我想要更新我的视图并用他们拥有的位置重绘一些目标。

我的GameView渲染功能和构造函数:

//Constructor
public GameView(){
        frame = new JFrame("Hunter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        drawing = new MyDrawing();
        drawing.setDoubleBuffered(true);;
        drawing.setIgnoreRepaint(true); 
        frame.getContentPane().add(BorderLayout.CENTER,drawing);
        frame.setResizable(false);
        frame.setSize(800,600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

//Render method where i want to draw all the object. (called form another class)
public void Render(ArrayList<Target> targets){
        //drawing is a MyDrawing object see next code.
        // i clear the jpanel with a white background
        drawing.drawBackground();

        // Loop al targets and paint them
        for (Target target : targets) {
            drawing.paintComponent(target.getX(), target.getY(), target.getSize());
        }           
    }

MyDrawing类。

public class MyDrawing extends JPanel {

    //Paint a target            
    public void paintComponent( int x, int y, int size){
        Graphics g = getGraphics();
        g.setColor(Color.black);
        g.fillOval(x, y, size, size);
    }

    public void drawBackground(){
        Graphics g = getGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, this.getWidth(),this.getHeight());
    }
}

从我的 GameController 中循环调用我的GameView中的渲染;

    public void Run(){
        while(notClosed){       
                Render();               
            }

            try {
                Thread.sleep(1000/100);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

    }

    public void Render(){
        myView.Render(myGame.getTargets());
    }

我想要的东西被画在屏幕上,但我看到一些闪光。特别是在jpanel的左侧,闪光灯非常明显。每隔x一次? secons整个屏幕闪烁。我在gameview的构造函数中调用setDubbelBuffer(true)。

0 个答案:

没有答案