gpt4 book ai didi

java - 如何制作一个透明的 JFrame 但保持其他一切不变?

转载 作者:太空狗 更新时间:2023-10-29 23:02:43 26 4
gpt4 key购买 nike

我想让 JFrame 透明,但它上面的图像是不透明的。这就是我现在拥有的:

enter image description here

有谁知道只使 JFrame 透明的方法吗?

这是我的代码:

import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;

public class SplashDemo extends JFrame
{
public SplashDemo()
{
setUndecorated(true);
setSize(200, 200);

add(new JLabel(new ImageIcon("puppy2.png")));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);

setOpacity(0.85f);
}

public static void main(String[] args)
{
new SplashDemo();
}
}

最佳答案

基本上,您需要制作一个透明的窗口和一个半透明的内容 Pane 。这意味着添加到内容 Pane 的任何内容都将继续呈现而无需额外的字母处理......

enter image description here

public class TranscluentWindow {

public static void main(String[] args) {
new TranscluentWindow();
}

public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}

JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}

}
});
}

public class TranslucentPane extends JPanel {

public TranslucentPane() {
setOpaque(false);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());

}

}

}

关于java - 如何制作一个透明的 JFrame 但保持其他一切不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14927980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com