简体   繁体   English

如何在JFrame中创建独立的JPanel-Layers并分别重新绘制每个图层

[英]How to create independent JPanel-Layers within JFrame and repaint each indiviually

I'm searching for a way to paint several JComponents above each other (overlap) and still being able to individually access and alter them. 我正在寻找一种将几个JComponents彼此绘制(重叠),并且仍然能够单独访问和更改它们的方法。

Eg paint three JPanels with transparent backgrounds - each containing a circle, a rectangle or a line. 例如,绘制具有透明背景的三个JPanels每个JPanels包含一个圆,一个矩形或一条线。 Afterwards, I'd like to change the appearance of the circle. 之后,我想更改圆圈的外观。 The other two should not be repainted (similarly to layers in Photoshop). 不应重绘其他两个(类似于Photoshop中的图层)。

My current project has a Jpanel with thousands of lines and I need to change a rectangle in the back on mouseover if I redraw the complete Jpanel each time it is very laggy. 我当前的项目有一个包含数千行的Jpanel ,如果每次鼠标Jpanel都重新绘制完整的Jpanel ,则需要在鼠标悬停时在背面更改一个矩形。

Is there a decent way to accomplish that? 有没有做到这一点的体面方法? Thank you already for your ideas! 已经感谢您的想法!

I need to change a rectangle in the back 我需要在后面更改一个矩形

You can invoke: 您可以调用:

panel.repaint(rectangle); // or 
panel.repaint(x, y, width, height);

to specify the Rectangular area to be repainted. 指定要重新绘制的矩形区域。

It worked quite fine - here is my code if anyone else has a similar problem! 它工作得很好-如果有人遇到类似问题,这是我的代码! the first image can be stored and displayed later on (buff) Make sure to generate new BufferedImage (here canvas) when displaying again, as the transperency is lost otherways. 可以存储第一个图像,并稍后在其上显示(buff)。请确保在再次显示时生成新的BufferedImage(此处为画布),否则会丢失透明度。 Thanks to Gilbert Le Blanc 感谢吉尔伯特·勒布朗克

@Override
protected void paintComponent(Graphics g1) {
    //Create image:
    BufferedImage buff = new BufferedImage(mywidth, myheight, BufferedImage.TYPE_INT_ARGB);

    //write to image:
    Graphics2D g2 = (Graphics2D) buff.getGraphics();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,(float) 0.01f));
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.draw(xxxRectanglewhatever);

    //then - later draw image again
    BufferedImage canvas = new BufferedImage(mywidth, myheight, BufferedImage.TYPE_INT_ARGB);
    canvas.getGraphics().drawImage(buff, 0, 0, null);
    ((Graphics2D) g1).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g1.drawImage(canvas, 0, 0, null);
    canvas.flush();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM