2014-02-24 33 views
0

即使在重繪導致可變位置改變之後,我仍然需要製作一個需要先前圖形的小程序以保持「放置」並可見。調用repaint()而不會丟失先前的圖形

public void paint(Graphics g){ 
    super.paint(g); 

    g.setColor(Color.red); 
    g.fillOval(mouseLocX,mouseLocY,30,30); 

} 

這是所有我在油漆類,我想改變mouseLocX和mouseLocY值,並調用重繪不必有以前的位置。我以前做過這個,大多數人都想要相反的,但我忘了。我使用mouseDragged()從MouseMotionListener調用repaint;

+0

你是什麼意思「以前的位置」?根據你的代碼片段,將被繪製的唯一值是'mouseLocX'和'mouseLocY'的當前值......紅色...... – MadProgrammer

回答

1

如果你想保留已經被繪的東西,以便在鼠標移動時獲得紅色橢圓而不是單個紅色橢圓,那麼你不應該直接在paint()提供的Graphics對象上繪製。相反,使用BufferedImage來存儲你的狀態。然後將BufferedImage渲染到paint()提供的圖形上。

private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 

public void paint(Graphics g) { 
    super.paint(g); 

    Graphics imageGraphics = image.getGraphics(); 
    imageGraphics.setColor(Color.red); 
    imageGraphics.fillOval(mouseLocX,mouseLocY,30,30); 

    g.drawImage(image, 0, 0, null); 
} 

BufferedImage爲以前的繪製操作提供了持久性。

+0

噢,這就是問題的含義?現在有意義;) –

相關問題