本人写了个橡皮筋画线,用鼠标监听,调用repaint()刷新重画直线,在画线的时候,窗口闪得厉害,我想知道怎样修改,能使窗口不闪啊

解决方案 »

  1.   

    是不是拖拽鼠标的时候,不断刷新导致闪烁。
    《java2 入门经典》里面讲过这个问题,好像是通过Graphics2D的setXORMode方法.....
      class MouseHandler extends MouseInputAdapter {
        public void mousePressed(MouseEvent e)  {
          start = e.getPoint();                             // Save the cursor position in start
          if(button1Down = (e.getButton() == MouseEvent.BUTTON1)) {
            g2D = (Graphics2D)getGraphics();                    // Get graphics context
            g2D.setXORMode(getBackground());                    // Set XOR mode *********
            g2D.setPaint(theApp.getWindow().getElementColor()); // Set color
          }
        }    public void mouseDragged(MouseEvent e) {
          last = e.getPoint();                              // Save cursor position      if(button1Down) {
            if(tempElement == null) {                       // Is there an element?
              tempElement = createElement(start, last);     // No, so create one
            } else {
              g2D.draw(tempElement.getShape());             // Yes - draw to erase it *******先擦掉旧的
              tempElement.modify(start, last);              // Now modify it 
            }
            g2D.draw(tempElement.getShape());               // and draw it
          }
        }
      

  2.   

    是因为帧数刷新的问题,  当你repaint()的时候是一帧一振的画,所以会有闪动的轨迹.
    要解决这个问题,就是在后台全部画好了直接将图片贴上来,起到立即刷新的效果.而不是一点点的刷新
    则:
    在repaint()之前,JVM自动会调用update()方法,所以你在update()里:        Image tempImage = null;         public void update(Graphics g){//调用paint()会先调用这个方法.
    if(tempImage==null){
    tempImage = this.createImage(400,300);//根据该当前的窗口创建一幅图像。 
    }
    Graphics imageG = tempImage.getGraphics();//要想在这个图片上作画,所以必须得到这个图像的Graphics.
    Color c = imageG.getColor();             
    imageG.setColor(Color.GREEN);            //将这个画笔设置为之前的颜色.
    imageG.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);         //画一个绿色的矩形. 达到刷新显示屏的效果
    imageG.setColor(c);                      
    paint(imageG);                          //把之前那些东西都在画在这个图片上.
      g.drawImage(tempImage,0, 0, 400, 300, null);  //把这个图片一次性的画到显示屏来.
    }
      

  3.   

    最好使用双缓存.还有另一个办法是:
    楼主在paint()方法后在的类中再写一个方法:
    public void update(Graphics g){}再把paint()方法里的代码复制复制到这个update方法内.就不闪了.