Java Swing: Clearing custom painting from a JPanel overlayed with other JPanels in a JLayeredPane

被刻印的时光 ゝ 提交于 2019-12-08 00:44:23

问题


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?


回答1:


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.




回答2:


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();



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!