gpt4 book ai didi

java - 未修饰的 JFrame 阴影

转载 作者:行者123 更新时间:2023-12-04 00:32:27 26 4
gpt4 key购买 nike

如何给未修饰的 jframe 添加阴影?

根据我在网上找到的信息,您可以将 jframe 添加到另一个黑色半透明窗口以产生阴影效果。或者以某种方式将类似的东西应用于 JFrame:

    Border loweredBorder = new EtchedBorder(EtchedBorder.LOWERED);
setBorder(loweredBorder);

无论哪种方式,我只想知道最好的方法,或者可能是一种完全不同的方式来获得相同的效果,比如从另一个类而不是 jframe 扩展。我是 Java 的新手,所以我可能会走错方向,因此不胜感激任何建议。

最佳答案

基本上,您需要制作一系列图层。

  • JFrame
  • 阴影面板
  • 和内容...

enter image description here

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class ShadowWindow {

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

public ShadowWindow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ShadowPane());

JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Look ma, no hands"));

frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class ShadowPane extends JPanel {

public ShadowPane() {
setLayout(new BorderLayout());
setOpaque(false);
setBackground(Color.BLACK);
setBorder(new EmptyBorder(0, 0, 10, 10));
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fillRect(10, 10, getWidth(), getHeight());
g2d.dispose();
}
}
}

关于java - 未修饰的 JFrame 阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19105242/

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