Re: Mysterious vanishing/flickering image prblem
fiziwig wrote:
I'm trying to draw a grid on a JLayeredPane. My JPane contains a menu,
a toolbar and the layered pane.
What happens is the grid flashes briefly on the screen then disappears.
Then, when I resize the window by dragging the border the grid flashes
and flickers, but ultimately disappears when I stop dragging.
FWIW: Here's the solution I found after trying about 12 different
approaches, including subclassing JComponent (which didn't work right),
and using a glass pane on my JFrame, which put the grid on the caption
bar as well.
Here's what DID work: I replaced my JLayeredPane with this class:
class GridPane extends JLayeredPane {
private BufferedImage grid;
private boolean gridShowing;
private int width,height;
public GridPane() {
super();
gridShowing = false;
width = 1024; // default sizes. The grid image will only be
created
height = 768; // once unless the window is resized to bigger
than this
}
public void paintComponent(Graphics g) {
// Override paint component to be able to superimpose grid
super.paintComponent(g); // paint background
if (!gridShowing) {
return;
}
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(grid, null, 0, 0);
}
public void showGrid(boolean value) {
gridShowing = value;
if (grid==null) {
makeGrid();
}
}
public void setSize( Dimension d ) {
super.setSize( d );
gridResize();
}
public void setSize( int w, int h ) {
super.setSize( w, h );
gridResize();
}
public void setBounds( int x, int y, int w, int h ) {
super.setBounds( x, y, w, h );
gridResize();
}
private void gridResize() {
if ((getWidth()>width)||(getHeight()>height)) {
// window has exceeded max size. redraw grid bigger
makeGrid();
}
}
private void makeGrid() {
// build a grid image at least as big as the window, but no
less than 1024x768
// This prevents having to create fresh images over and over
while dragging
// the edge of the window to resize, thus preventing the
garbage collector from
// having a nervous breakdown.
int x,y;
width = getWidth();
if (width<1024) {
width = 1024;
}
height = getHeight();
if (height<768) {
height = 768;
}
grid = (BufferedImage)(createImage(width,height));
Graphics2D gc = grid.createGraphics();
gc.setColor( new Color(0xd0d0ff));
for (x=0; x<width; x+=10) {
gc.drawLine(x, 0, x, height);
}
for (y=0; y<height; y+=10) {
gc.drawLine(0, y, width, y);
}
}
}
--gary