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?
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
.
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();
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.
来源:https://stackoverflow.com/questions/5660704/java-swing-clearing-custom-painting-from-a-jpanel-overlayed-with-other-jpanels