Java摆动/自动剪切透明背景叠加

问题描述 投票:0回答:1

我正在尝试使用不占据背景的裁剪区域制作透明背景。有点像Windows截图工具,当您拖动矩形时,该矩形周围的所有内容都被白色透明覆盖层覆盖,除了您拖动矩形的区域。

现在,我想知道是否可以使用JFrames和Graphics.setClip-Method来做到这一点。

可以用Java完成这样的事情吗?

java swing awt
1个回答
1
投票

也许您正在寻找这样的东西:

enter image description here

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;

public class FrameTranslucent2 extends JFrame
{
    public FrameTranslucent2()
    {
        super("Frame Translucent");

        setBackground(new Color(0,0,0,0));
        setSize(new Dimension(600,600));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new BorderLayout())
        {
            @Override
            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;

                //  Simple approach to make a rectangular area fully transparent

                g2d.clearRect(100, 100, 200, 200);

                //  Make a Shape area fully transparent
/*
                Shape inner = new Ellipse2D.Double(100, 100, 200, 200);
                g2d.setClip( inner );
                g2d.clearRect(0, 0, getWidth(), getHeight());
*/
            }
        };

        panel.setBackground( new Color(128, 128, 128, 64) );
        setContentPane(panel);
    }

    public static void main(String[] args)
    {
        // Determine what the GraphicsDevice can support.

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        boolean isPerPixelTranslucencySupported = gd.isWindowTranslucencySupported(PERPIXEL_TRANSLUCENT);

        //If translucent windows aren't supported, exit.

        if (!isPerPixelTranslucencySupported)
        {
            System.out.println("Per-pixel translucency is not supported");
            System.exit(0);
        }

        JFrame.setDefaultLookAndFeelDecorated(true);

        // Create the GUI on the event-dispatching thread

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run() {
                FrameTranslucent2 gtw = new FrameTranslucent2();

                // Display the window.
                gtw.setVisible(true);
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.