Inner-Transparent Selection Window in Java using GlassPane

这一生的挚爱 提交于 2019-11-29 14:42:27

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

As Andrew has suggested (just beat me while I was finishing off 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();
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!