Alpha Composite Question

Howdy, quick question here.

I have a program that will draw 4 squares on the screen with a second smaller square (call this the icon) on 1 of the 4.

I can then drag the icon around and place it on another squares. So I can move it to anyplace I want on these squares. The problem is when I am dragging the icon around, it goes under some of the squares - which is not desired, but over some of them - which is desired.

I looked at the tutorials and it say to use an alpha composite with SRC (or SRC_OVER, too iirc). Here is my paintComponent method:


public void paintComponent(Graphics g) 
	{
	    clear(g);
	    Graphics2D g2d = (Graphics2D)g;
	    
	  
	    	g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
		    for(int i=0;i<idata.length;i++)
		    {
		    	       	//place the squares, as buffered images with g2d.drawImage on the screen
		    }
 
 
    
		g2d.draw(square); //this is just a border.
	  }


When I run this code, no change happens. Sometimes the icon will go over, other times it will go under.

I have a feeling I am missing something here but I am not sure.

Thank you for any help.>

This is what I use:

         Composite originalComposite = g.getComposite();
         g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25f));
         g.setColor(Color.WHITE);
         g.fillRect(x, y, w, h);
         g.setComposite(originalComposite); 

This paints a rectangle 25% visible.

You’re missing the float value on the alpha.

Thank you for your reply. I managed to get the AC to work …but…

it still does not force the icon as it moves over some of them to appear above all of the other images? Do you know how to do that? I am thinking that the AC is not what I want now.

Thanks!

Not sure but I believe that it has something to do with the order in which you are drawing the squares

Nice catch!! This was exactly it.

Works like a charm now!

Thank you.

One catch with using alpha compositing with Swing components is that you must fill every pixel
of the component, or declare it as non-opaque by calling .setOpaque(false).

Otherwise you will get rendering artifacts since Swing’s repainting mechanism relies
on this and will not repaint stuff under your component.

Thanks,
Dmitri