email me at borlaj@portlandschools.org

Loading
notes previous (10/<10) submit the dump links  
 

ColorChooser

 

Color selectedColor = JColorChooser.showDialog(this, "Choose Color", getBackground());

Color chooser is really nice, but it will erases anything that you have drawn to the screen. The reason this happens is that after it runs, it it calls paint and draws the original components.

 

One fix for this is to use bufferGraphics. The idea is we are going to do all our drawing on a seperate image and then paste it to the screen.

To do that we need to create a new image and graphics object to draw on, which I will call bufferedImage and buffergraphics and I will save as globals:

 

First I import necessary library:

import java.awt.image.*;

Then in my globals

BufferedImage bufferedImage;
Graphics bufferGraphics;

 

Now, I will initialize them in my init statement as below:

bufferedImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);

bufferGraphics = bufferedImage.getGraphics();

 

Now anytime that I draw, I will draw on bufferGraphics. So if in mouseMoved I said

bufferGraphics.setColor

bufferGraphics.drawOval

To paint it you might call repaint or below:

 

Now in paint, after I redraw the components with super.paint(g), I will say

g.drawImage(bufferedImage,0,0,this);

which draws the bufferedImage to the screen.