skip to Main Content

I’m searching for a way to paint several JComponents above each other (overlap) and still being able to individually access and alter them.

E.g. paint three JPanels with transparent backgrounds – each containing a circle, a rectangle or a line.
Afterwards, I’d like to change the appearance of the circle. The other two should not be repainted (similarly to layers in 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.

Is there a decent way to accomplish that? Thank you already for your ideas!

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search