In-Transparent Selection Window in Java using GlassPane

I am trying to achieve the following

http://www.qksnap.com/i/3hunq/4ld0v/screenshot.png

Currently, I can draw rectangles on a translucent glass background using the following code:

protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g.setColor(Color.black); // black background g.fillRect(0, 0, frame.getWidth(), frame.getHeight()); g2.setColor(Color.GREEN.darker()); if (getRect() != null && isDrawing()) { g2.draw(getRect()); // draw our rectangle (simple Rectangle class) } g2.dispose(); } 

Which works fine, however, I would like the area inside the rectangle to be completely transparent and the outside to be still dark, as in the screenshot above.

Any ideas?

+4
source share
2 answers

.. the area inside the rectangle will be completely transparent, while the outer side is still dark, as in the screenshot above.

  • Create a Rectangle ( componentRect ) whose size will be colored.
  • Create an Area ( componentArea ) of this form ( new Area(componentRect) ).
  • Create an Area ( selectionArea ) selectionRectangle .
  • Call componentArea.subtract(selectionArea) to remove the selected part.
  • Call Graphics.setClip(componentArea)
  • Draw a translucent color.
  • (Clear the clipping area if more drawing operations are required).
+5
source

As Andrew said (just beat me while I was finishing my example)

 protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g.setColor(Color.black); // black background Area area = new Area(); // This is the area that will filled... area.add(new Area(new Rectangle2D.Float(0, 0, getWidth(), getHeight()))); g2.setColor(Color.GREEN.darker()); int width = getWidth() - 1; int height = getHeight() - 1; int openWidth = 200; int openHeight = 200; int x = (width - openWidth) / 2; int y = (height - openHeight) / 2; // This is the area that will be uneffected area.subtract(new Area(new Rectangle2D.Float(x, y, openWidth, openHeight))); // Set up a AlphaComposite g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g2.fill(area); g2.dispose(); } 

Show and hide

+5
source

All Articles