Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

swing - Inner-Transparent Selection Window in Java using GlassPane

I am trying to achieve the following

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

I am currently able to draw rectangles successfully on a semi-transparent glasspane 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 great, however, I would love to have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

..have the area within the rectangle be completely transparent while the outside was still darken much like the screenshot above.

  • Create a Rectangle (componentRect) that is the size of the component being painted.
  • Create an Area (componentArea) of that shape (new Area(componentRect)).
  • Create an Area (selectionArea) of the selectionRectangle.
  • Call componentArea.subtract(selectionArea) to remove the selected part.
  • Call Graphics.setClip(componentArea)
  • Paint the semi-transparent color.
  • (Clear the clipping area if more paint operations are required).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...