0

I have a frame with image inside and I want to choose part of that image with my own component (extending JComponent). Now it looks like that:

enter image description here

But I want it to look something like that:

enter image description here

How can I achieve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Krzysztof Majewski
  • 2,494
  • 4
  • 27
  • 51
  • 1
    If the original image is with the bluish tint, it only requires painting a reddish partially transparent color around the **outside** of the selection box. 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Aug 03 '15 at 16:16
  • 1
    *"extending java.awt.Component"* As an aside, if this is a Swing GUI, use a `JComponent` or a `JPanel` instead. – Andrew Thompson Aug 03 '15 at 16:18
  • 1
    *"..requires painting a reddish partially transparent color around the outside of the selection box"* It would be a minor variation of [this code](http://stackoverflow.com/a/11007422/418556).. – Andrew Thompson Aug 03 '15 at 16:25

1 Answers1

1

It really depends on how you are drawing your component. If you are using a Graphics, you can cast it to a Graphics2D and then you can either setPaint, or setComposite to get a transparency effect.

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;

/**
 * Created by odinsbane on 8/3/15.
 */
public class TransparentOverlay {

    public static void main(String[] args){

        JFrame frame = new JFrame("painting example");

        JPanel panel = new JPanel(){

            @Override
            public void paintComponent(Graphics g){
                Graphics2D g2d = (Graphics2D)g;
                g2d.setPaint(Color.WHITE);
                g2d.fill(new Rectangle(0, 0, 600, 600));
                g2d.setPaint(Color.BLACK);
                g2d.fillOval(0, 0, 600, 600);

                g2d.setPaint(new Color(0f, 0f, 0.7f, 0.5f));
                g2d.fillRect(400, 400, 200, 200);

                g2d.setPaint(Color.GREEN);
                g2d.setComposite(
                    AlphaComposite.getInstance(
                        AlphaComposite.SRC_OVER, 0.8f
                    )
                );

                g2d.fillRect(0,0,200, 200);
                g2d.setPaint(Color.RED);
                g2d.fillRect(400, 0, 200, 200);
            }
        };

        frame.setContentPane(panel);
        frame.setSize(600, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

}

With a set composite, all of your drawing afterwards will have the same composite, until you change it again.

matt
  • 10,892
  • 3
  • 22
  • 34