2

I've got a JLayeredPane containing three JPanels, two of which overlap, that I'm painting shapes to. One of the two JPanels that overlap needs to have every shape drawn to it cleared without affecting the shapes drawn to the JPanel under it disappear from the screen. Currently I'm using something like this:

    Graphics g = pane2.getGraphics(); 
    g.clearRect (0, 0, 1000, 1000);

But this not only clears everything painted to pane2 but also pane1, which is under it. So my question is: Is there any way to clear everything painted to one JPanel without affecting anything painted to a JPanel under it?

jzd
  • 23,473
  • 9
  • 54
  • 76
JBenson
  • 293
  • 2
  • 5
  • 13

3 Answers3

3

Make sure your panels are non-opaque. I would think you need code like:

Graphics g = pane2.getGraphics();      
g.clearRect (0, 0, 1000, 1000); 
pane2.repaint(0, 0, 1000, 1000);

Or you should be able to use the following to force a repaint of all the panels:

layeredPane.repaint();
camickr
  • 321,443
  • 19
  • 166
  • 288
2

I think you can clear it that way then just paint it the standard way. Something like:

Graphics g = pane2.getGraphics(); 
g.clearRect (0, 0, 1000, 1000);
super.paintComponent(g);

You might also need to repaint the bottom JPanel.

If you cannot repaint the bottom JPanel--if, for example, you do not have a list of the shapes anywhere--then I suspect that it may not be possible to recover on the bottom JPanel.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214
  • But clearing it that way not only clears everything on that JPanel, but everything on the JPanel below it. I need to keep everything painted to the JPanel below it stay there. – JBenson Apr 14 '11 at 09:00
  • Oh, I think you might need to repaint the JPanel below it then. – Tikhon Jelvis Apr 14 '11 at 09:01
  • How exactly do you keep track of the shapes you paint? Do you have some ArrayList or something holding them, or do you just paint them to the JFrame and lose them afterwards? – Tikhon Jelvis Apr 14 '11 at 09:12
  • Currently they're just painted and then lost, I thought that actions on one JPanel wouldn't affect the JPanel under it. Am I wrong about this? – JBenson Apr 14 '11 at 09:30
2

I think you should use clip to set regions which should not be replaced. In the panel 2 detecty which area should not be damaged and create roper rectangle(s). Then create a clip area. Rectangle with subtracted area. See Area class to subtract shape.

StanislavL
  • 56,971
  • 9
  • 68
  • 98